Method for automatic detection of the height and width of a thermal printer sheet based on a large model

By using image acquisition and processing technology based on large models, the automatic detection of paper height and width in thermal printers has been achieved, solving the accuracy and adaptability problems of traditional detection methods and improving the ease of use and automation of printers.

CN122156286APending Publication Date: 2026-06-05ZHUHAI XPRINTER ELECTRONICS TECHNOLOGY CO LTD

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
ZHUHAI XPRINTER ELECTRONICS TECHNOLOGY CO LTD
Filing Date
2026-01-12
Publication Date
2026-06-05

AI Technical Summary

Technical Problem

Existing thermal printer paper detection technology cannot accurately obtain paper width information, relies on manual settings which are prone to errors, mechanical parts are easily worn and have high maintenance costs, cannot adapt to diverse paper sizes, and reduces printing efficiency and automation.

Method used

Employing image acquisition and processing technology based on large models, paper images are captured by a camera. Combined with visual large model segmentation and perspective correction, the height and width of the paper are automatically detected. Through real-time calibration and intelligent early warning mechanisms, high-precision detection without human intervention is achieved.

Benefits of technology

It enables a place-and-print experience without human intervention, adapts to diverse paper sizes, reduces mechanical wear and maintenance costs, improves detection accuracy and printing process stability, and reduces paper waste and equipment failure.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122156286A_ABST
    Figure CN122156286A_ABST
Patent Text Reader

Abstract

The application discloses an automatic detection method for the height and width of thermal printer paper based on a large model, aiming at solving the problems of single detection dimension, limited precision, and complicated operation existing in the current mechanical detection or manual setting. The method collects the image containing the paper and the reference marker through the camera, and after pretreatment such as Gaussian filtering and histogram equalization, uses the Segment Anything Model for image segmentation and region positioning, eliminates distortion by combining perspective correction, establishes the conversion relationship between pixels and actual size through the reference marker, and realizes accurate calculation of the height and width of the paper. In the printing process, dynamic calibration is combined with the stepping motor data, and paper type identification and intelligent early warning functions are added. The application adopts a non-contact visual detection scheme, does not require manual intervention, has high detection precision and wide adaptability, can reduce equipment maintenance cost, avoid printing interruption and resource waste, and improve the intelligent level and use convenience of the thermal printer.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention belongs to the field of printer technology, and particularly relates to an automatic detection method for the height and width of thermal printer paper based on a large model. Background Technology

[0002] Thermal printers, as a common printing device, are widely used in commercial and office scenarios such as retail POS, logistics waybill printing, and medical prescription printing due to their advantages of fast printing speed, low noise, and compact structure. During the use of thermal printers, accurate paper size matching is a key prerequisite for ensuring print quality and avoiding printing malfunctions. Different scenarios require the adaptation of various specifications of thermal paper, including rolls or sheets of different widths and lengths.

[0003] Currently, thermal printers primarily rely on traditional mechanical detection methods or manual settings to detect paper size. Mechanical detection typically involves installing a mechanical microswitch or photoelectric sensor at a specific location inside the printer. When the edge of the paper passes the sensor, a signal is triggered, thus detecting the paper's length. However, this method has significant drawbacks: firstly, the sensor can usually only detect the length of the paper, not its width. Users must manually select or input the paper width parameter in the driver software or on the printer panel, a cumbersome process prone to errors that can lead to misaligned printouts and wasted paper. Secondly, long-term use of mechanical components causes wear and tear, resulting in decreased detection accuracy and signal triggering failure, increasing equipment maintenance costs and impacting printing efficiency. Manual settings, on the other hand, rely entirely on the user's prior knowledge of the paper size and manual configuration. This not only fails to adapt to diverse paper sizes but also results in high repetitiveness in scenarios involving frequent paper type changes, significantly reducing the automation level of the printing process.

[0004] With the development of intelligent and automated technologies, modern office and commercial scenarios place higher demands on the ease of use, accuracy of detection, and adaptability of thermal printers. The limitations of traditional detection methods are becoming increasingly apparent, failing to meet the needs for no manual intervention, high-precision detection, and adaptability to multiple paper sizes. Therefore, there is an urgent need for a technical solution that can automatically and accurately detect the height and width of thermal printer paper to address the shortcomings of existing technologies. Summary of the Invention

[0005] The purpose of this invention is to provide an automatic detection method for the height and width of thermal printer paper based on a large model, comprising the following steps: S1. Image Acquisition: The thermal printer uses a built-in or external camera to capture images of the paper area inside the printer, ensuring that the image captures the entire paper area and preset reference markers. S2. Image preprocessing: Denoise, contrast enhancement and binarization are performed on the image acquired in step S1 to highlight the difference between the paper area and the background, and to provide clear image data for subsequent area detection. S3. Image Segmentation and Region Localization: The visual large model is called to segment the preprocessed image, obtain the segmentation mask of the paper area and reference markers, and accurately locate the specific position of the paper in the image. S4. Perspective Correction: For the paper area located in step S3, determine whether there is perspective distortion. If so, extract the four corner points of the paper and perform perspective transformation to obtain the front view of the paper. S5. Calculation of reference marker size: Based on the reference marker segmentation mask obtained in step S3, calculate the pixel size of the reference marker in the image; S6. Establish the proportional conversion relationship: Based on the known actual physical size of the reference marker and the pixel size calculated in step S5, establish the proportional conversion relationship between image pixels and actual physical size; S7. Paper pixel size acquisition: Based on the paper area located in step S3 and the front view obtained in step S4, calculate the pixel height and pixel width of the paper in the image. S8. Actual size conversion: Using the proportional conversion relationship established in step S6, convert the paper pixel height and pixel width obtained in step S7 into actual physical height and actual physical width; S9. Real-time calibration: During the printing process, repeat steps S1 to S8 to continuously acquire paper images and perform size detection, dynamically calibrate the actual height and width data of the paper to ensure detection accuracy; S10. Intelligent Early Warning: Based on the actual paper height data after calibration in step S9, combined with the paper length required for the printing task, the remaining paper usage is determined in real time. When the remaining usage is lower than the preset threshold, an early warning prompt is triggered.

[0006] In a further embodiment of the present invention, in step S1, the installation position of the camera is fixed and the acquisition angle is determined by pre-adjustment to ensure that the relative position of the reference marker and the paper remains stable in each acquired image.

[0007] In a further embodiment of the present invention, in step S3, the large visual model is SegmentAnythingModel, which achieves accurate segmentation of the paper area and reference markers through zero-sample segmentation.

[0008] In a further embodiment of the present invention, in step S4, the perspective distortion judgment is achieved by detecting the pixel distribution characteristics of the four edges of the paper. When the edge pixel distribution is non-parallel, it is determined that perspective distortion exists.

[0009] In a further embodiment of the present invention, in step S1, the reference marker is a known-sized structural component fixedly installed inside the printer, or a standard-sized object placed next to the paper, and the actual physical size of the reference marker is pre-stored in the printer control system.

[0010] In a further embodiment of the present invention, in step S2, the image denoising adopts a Gaussian filtering algorithm, the contrast enhancement adopts a histogram equalization algorithm, and the binarization process adopts an adaptive threshold segmentation algorithm.

[0011] In a further embodiment of the present invention, in step S9, the frequency of dynamic calibration is synchronized with the operating frequency of the printer stepper motor, and a calibration process is performed once every preset number of motor runs.

[0012] In a further embodiment of the present invention, a paper type identification step is also included, specifically: extracting the texture features and reflective properties of the paper in the image after preprocessing step S2 using a large visual model, comparing it with a preset database of various paper features, determining the paper type, and automatically matching the optimal printing density and printing speed parameters according to the paper type.

[0013] In a further embodiment of the present invention, in step S8, when the calculated actual height and width of the paper exceed the printer's preset adaptation range, the printer control system issues an abnormal prompt and suspends the printing task.

[0014] In a further embodiment of the present invention, in step S3, if the visual large model segmentation fails to obtain the paper area or reference marker, a backup detection mechanism is activated, and the paper area and reference marker are repositioned through edge detection algorithm and contour extraction algorithm before proceeding with subsequent steps.

[0015] The beneficial effects of this invention are: 1. This invention uses a camera to capture images and combines visual large model segmentation, size conversion and real-time calibration to automatically complete the detection of paper height and width without manual intervention. Users do not need to manually set paper size parameters, realizing a "place and print" user experience, which significantly reduces the operation threshold, avoids printing failures caused by human operation errors, and is suitable for scenarios with frequent switching of diverse paper specifications.

[0016] 2. A non-contact visual inspection solution is adopted, replacing traditional easily worn mechanical parts, effectively avoiding the problem of decreased inspection accuracy caused by mechanical wear; image quality is optimized through image preprocessing, and errors caused by shooting angle are eliminated by perspective correction; a precise pixel-to-actual size conversion relationship is established using reference markers; and the inspection data is dynamically corrected through a real-time calibration mechanism to ensure high accuracy of paper size inspection and stability of long-term printing, thus providing a guarantee for high-quality printing.

[0017] 3. Not only can it accurately detect the size of standard paper, but it can also adapt to special non-standard paper sizes. Through a large visual model, it can accurately segment and calculate the size of paper areas without the need for equipment debugging or parameter settings for different paper sizes. At the same time, the newly added paper type recognition step can automatically match the optimal printing density and speed parameters by extracting paper texture features and reflective properties, meeting the printing needs of different types of paper such as ordinary thermal paper, synthetic paper, and label paper, and adapting to special application scenarios in multiple industries such as retail, logistics, and medical.

[0018] 4. It abandons the traditional detection method that relies on mechanical sensors, reduces the number of easily worn parts inside the equipment, and lowers the frequency of failures and repairs caused by mechanical wear. At the same time, the combination of large visual models and traditional computer vision algorithms gives the detection system strong environmental adaptability and anti-interference ability, reduces the impact of the external environment on the detection results, thereby extending the overall service life of the printer and reducing the maintenance cost of the entire equipment life cycle.

[0019] 5. By obtaining the actual height data of the paper through real-time calibration and combining it with the paper length required for the printing task, the remaining paper usage is dynamically calculated. When the remaining usage is lower than the preset threshold, an early warning prompt is triggered to remind the user to replace the paper in time. This effectively avoids problems such as printing interruption and incomplete information caused by running out of paper during long printing tasks, reduces the waste of paper and printing consumables, and improves the continuity and efficiency of the printing process.

[0020] 6. When the visual large model segmentation fails to successfully acquire the paper area or reference marker, the backup detection mechanism of edge detection and contour extraction is activated to ensure the continuous operation of the detection process, avoid equipment downtime due to the failure of a single detection method, and improve the reliability and robustness of the entire detection system. Attached Figure Description

[0021] Figure 1 This is a schematic diagram of the steps of the present invention. Detailed Implementation

[0022] The technical solutions of the embodiments of this application will be clearly described below with reference to the accompanying drawings. Obviously, the described embodiments are only some, not all, of the embodiments of this application. All other embodiments obtained by those skilled in the art based on the embodiments of this application are within the scope of protection of this application.

[0023] In the description of this application, it should be noted that the terminology used herein is for the purpose of describing particular embodiments only and is not intended to limit the exemplary embodiments according to this application. For ease of description, the dimensions of the various parts shown in the drawings are not drawn to actual scale. Techniques, methods, and devices known to those skilled in the art may not be discussed in detail, but where appropriate, such techniques, methods, and devices should be considered part of the specification. In all examples shown and discussed herein, any specific values ​​should be interpreted as merely exemplary and not as limitations. Therefore, other examples of exemplary embodiments may have different values. It should be noted that similar reference numerals and letters in the following drawings denote similar items; therefore, once an item is defined in one drawing, it need not be further discussed in subsequent drawings.

[0024] It should be noted that the terms "first," "second," etc., used in the specification and claims of this application are used to distinguish similar objects and not to describe a specific order or sequence. It should be understood that such use of data can be interchanged where appropriate so that embodiments of this application can be implemented in orders other than those illustrated or described herein, and the objects distinguished by "first," "second," etc., are generally of the same class and are not limited in number; for example, a first object can be one or more. Furthermore, in the specification and claims, "and / or" indicates at least one of the connected objects, and the character " / " generally indicates that the preceding and following objects are in an "or" relationship.

[0025] This embodiment provides an automatic detection method for the height and width of thermal printer paper based on a large model, including the following steps: S1. Image Acquisition: Using a high-definition camera built into or connected to the thermal printer, images of the paper placement area inside the printer are acquired. During acquisition, the camera's exposure parameters, shutter speed, and ISO are strictly controlled to ensure image clarity meets subsequent processing requirements. Simultaneously, the acquired image must completely include the top, bottom, left, and right edges of the paper and preset reference markers to avoid size detection errors due to missing image information. This step, by fixing key parameters of the acquisition scene, provides a complete and reliable image data source for subsequent size conversion, ensuring detection accuracy from the source. No manual intervention is required in the image acquisition process, improving the automation level of the detection workflow.

[0026] S2. Image Preprocessing: The original image acquired in step S1 is sequentially subjected to denoising, contrast enhancement, and binarization. For image denoising, a Gaussian filtering algorithm is used. A Gaussian filter kernel is constructed and convolved with the image to remove Gaussian noise. The Gaussian filtering formula is: In the formula, (x, y) represents the coordinates of a pixel within the filter kernel relative to the kernel center, and σ is the standard deviation of the Gaussian function. Adjusting the value of σ can balance the noise reduction effect and the degree of image detail preservation. Contrast enhancement uses a histogram equalization algorithm, which stretches the gray-level histogram of the image to make the gray-level distribution more uniform and enhance the gray-level difference between the paper area and the background. The specific process is as follows: first, calculate the gray-level histogram of the image, then solve the cumulative distribution function, and finally map the original gray-level values ​​to the equalized gray-level values ​​through the cumulative distribution function. Binarization processing uses an adaptive... The threshold segmentation algorithm dynamically determines the segmentation threshold based on the grayscale features of local image regions. The calculation formula is: T(x,y)=μ(x,y)+C, where T(x,y) is the binarization threshold of pixel (x,y), μ(x,y) is the average grayscale value in the neighborhood of pixel (x,y), and C is a constant offset. This algorithm can effectively handle the problem of uneven image illumination, accurately separate paper areas from background areas, provide image data with clear contours and less interference for subsequent region detection, and significantly improve the accuracy of subsequent segmentation and localization.

[0027] S3. Image Segmentation and Region Localization: A large-scale visual model, SegmentAnythingModel (SAM), is invoked to segment the preprocessed image. This model, trained on massive amounts of image data, possesses powerful zero-shot segmentation capabilities. It can accurately identify and segment paper regions and reference markers based on image semantic information without requiring specific sample annotation training for paper or reference markers, outputting corresponding segmentation masks. The segmentation masks mark the target regions with pixel-level precision. By analyzing the pixel coordinates of the segmentation masks, the specific location of the paper in the image can be accurately determined, including the pixel coordinate range of the paper edges and the complete pixel region of the reference markers. If the large-scale visual model segmentation fails to capture the paper region or reference marker, a backup detection mechanism is immediately activated. This mechanism re-locates the target region using the Canny edge detection algorithm and a contour extraction algorithm based on connected component analysis. The Canny algorithm extracts edge features from the image through four steps: Gaussian filtering to smooth the image, calculating gradient magnitude and direction, non-maximum suppression, and double threshold detection. The contour extraction algorithm traverses the pixels in the binarized image, classifying adjacent foreground pixels as connected components, and then extracts the contours of these connected components, which serve as the basis for locating the paper region and reference marker. This combination of primary and backup detection mechanisms ensures the reliability of region localization, preventing detection interruptions due to the failure of a single model. Simultaneously, the zero-shot segmentation characteristic of the SAM model reduces the system's training cost and improves its adaptability to different types of paper and reference markers.

[0028] S4. Perspective Correction: For the paper area located in step S3, the presence of perspective distortion is determined by analyzing the pixel distribution characteristics of the four edges of the paper. Specifically, the pixel coordinates of the four edges of the paper area in the segmentation mask are extracted, and the pixel-fitted straight line for each edge is calculated. If the slope difference between any two opposite edges exceeds a preset threshold, perspective distortion is determined to exist. If perspective distortion exists, the pixel coordinates of the four corner points of the paper are extracted, and a perspective projection matrix is ​​constructed to perform perspective transformation, obtaining the front view of the paper. The formula for the perspective projection matrix is: In this equation, (u,v) represents the original coordinates of a pixel in the perspective-distorted image, (u′,v′) represents the target coordinates of a pixel in the perspective-corrected image, w′ represents the homogeneous coordinate coefficients, and a11 to a32 represent the unknown parameters of the perspective transformation matrix. By substituting the original coordinates of the four corner points of the paper and the corrected target coordinates (presumably the coordinates of the four vertices of a rectangle) into the matrix equation, all unknown parameters are obtained, thus completing the perspective correction of the entire paper area. This step effectively eliminates the dimensional distortion caused by the camera's shooting angle, ensuring that subsequent dimensional calculations are based on the true geometry of the paper, significantly improving the accuracy of dimensional detection.

[0029] S5. Reference Marker Size Calculation: Based on the reference marker segmentation mask obtained in step S3, the number of pixels and pixel distribution range of the reference markers in the image are counted. For reference markers with regular shapes (such as rectangles and circles), if it is a rectangle, the minimum bounding rectangle of the reference marker in the segmentation mask is extracted, and the pixel width and pixel height of the minimum bounding rectangle are calculated, which are the pixel size of the reference marker; if it is a circle, the center coordinates and pixel radius of the reference marker are detected by the Hough circle detection algorithm, and then the pixel size in the diameter or perimeter direction is calculated; for reference markers with irregular shapes, the equivalent pixel size corresponding to the pixel length or area of ​​its outline is calculated to ensure that the pixel size calculation can accurately reflect the actual physical size ratio of the reference marker. This step provides key data support for establishing the conversion relationship between pixels and actual size by accurately calculating the pixel size of the reference marker.

[0030] S6. Establishing the Proportional Conversion Relationship: Based on the pre-stored actual physical size of the reference marker and the pixel size calculated in step S5, establish the proportional conversion relationship between image pixels and actual physical size. Let the actual physical size of the reference marker be L0 (unit: mm), and the corresponding pixel size be P0 (unit: pixels), then the formula for calculating the proportional conversion coefficient k is: (Unit: mm / pixel). The conversion factor k reflects the actual physical length corresponding to each pixel. The conversion relationship established by the reference marker can achieve accurate conversion from pixel size to actual physical size without relying on the camera's calibration parameters (such as focal length and sensor size), reducing the system's dependence on hardware parameters and improving the versatility and practicality of the solution.

[0031] S7. Paper Pixel Size Acquisition: Based on the paper region segmentation mask located in step S3 and the front view obtained in step S4, extract the complete pixel distribution range of the paper in the front view. Using the same method as the reference marker pixel size calculation in step S5, for rectangular paper, extract its minimum bounding rectangle and read its pixel width PW and pixel height PH; for non-rectangular paper, extract the pixel width and pixel height of its effective printing area according to the printing scenario requirements, ensuring that the acquired pixel size accurately corresponds to the actual usable size of the paper. This step uses the front view to measure the pixel size, avoiding the influence of perspective distortion on the measurement results and ensuring the accuracy of the pixel size data.

[0032] S8. Actual Size Conversion: Using the proportional conversion factor k established in step S6, the paper pixel height PH and pixel width PW obtained in step S7 are converted into the actual physical height LH and actual physical width LW. The conversion formulas are as follows: If the calculated actual paper height (LH) and width (LW) exceed the printer's preset adaptation size range (this range is preset based on hardware parameters such as the printer's print roller width and effective print head width), the printer control system immediately issues an abnormality warning (such as an audible and visual alarm or a text prompt on the display screen) and pauses the current printing task to prevent malfunctions such as overflowing print content or paper jams caused by paper size mismatch. This step achieves automatic acquisition of the actual paper size through precise size conversion, and at the same time, size adaptation judgment ensures the stability and safety of the printing process, reducing paper waste and equipment wear.

[0033] S9. Real-time Calibration: During printing, steps S1 to S8 are repeated at a preset frequency to continuously acquire paper images and perform size detection, dynamically calibrating the actual height and width data of the paper. The frequency of dynamic calibration is synchronized with the operating frequency of the printer's stepper motor. A calibration process is executed once after each preset number of motor steps. Let the paper feed distance corresponding to each stepper motor step be SStep (unit: mm / step), and the cumulative number of steps be N. Then, the paper size LStep calculated based on the number of stepper motor steps = SStep × N. During calibration, a multi-modal fusion algorithm is used to weightedly fuse the paper size LDet obtained from image detection with the paper size LStep calculated from the stepper motor data. The calibration formula is: Where LCal is the actual size of the calibrated paper, n is the weighting coefficient of the image detection data, and m is the weighting coefficient of the stepper motor data. n and m are dynamically adjusted according to the actual detection accuracy (e.g., n takes a larger value when the image detection accuracy is high, and m takes a larger value when the stepper motor runs stably). Through real-time calibration, dimensional deviations caused by factors such as paper offset and image acquisition errors during printing can be dynamically corrected, ensuring the accuracy and stability of detection data during long-term continuous printing and providing continuous assurance for high-quality printing.

[0034] S10. Intelligent Warning: Based on the actual paper height data LCal calibrated in step S9, combined with the single-page paper consumption length LTask of the current printing task and the number of printed pages nTask, the remaining paper usage LRem is calculated in real time. The formula for the remaining usage is: LRem = LCal - nTask × LTask. The remaining usage LRem is compared with a preset threshold LTh (set according to the actual application scenario, such as a threshold for reserving 1 - 2 pages of printing length) in real time. When LRem < LTh, the printer control system immediately triggers an intelligent warning prompt. The warning methods include audible and visual alarms, pop-up prompts on the display screen, software notifications on connected devices (such as computers and mobile phones), etc., to remind the user to replace the paper in a timely manner. This step can effectively avoid problems such as printing interruptions and incomplete information caused by paper exhaustion during long-task printing, ensuring the continuity of the printing process and reducing the time cost and resource waste caused by printing interruptions.

[0035] In step S1, the installation position of the camera is fixed. The camera is fixed at a preset position inside the printer through a bracket, and the acquisition angle is determined through pre-adjustment. During the adjustment process, it is ensured that the optical axis of the camera is perpendicular to the paper placement plane (or a fixed known angle), and the relative position of the reference marker and the paper in each captured image remains stable, that is, the pixel coordinate range of the reference marker in the image fluctuates no more than a preset threshold (such as ±5 pixels). This setting can avoid image acquisition deviations caused by changes in the camera position or angle, ensure the stability of the pixel size ratio relationship between the reference marker and the paper, and thus guarantee the consistency of the proportional conversion coefficient k, improving the repeatability and accuracy of size detection.

[0036] In step S3, the visual large model is SegmentAnythingModel (SAM). This model adopts an encoder-decoder architecture. The encoder extracts features from the preprocessed image to generate multi-scale image feature maps; the decoder combines the implicit target semantic information of the user (i.e., the paper and the reference marker) to perform segmentation processing on the feature maps and outputs pixel-level segmentation masks. The zero-shot segmentation ability of the SAM model enables it to adapt to papers and reference markers of different materials, colors, and specifications without sample training for specific targets, greatly improving the adaptability and deployment efficiency of the system. At the same time, its segmentation accuracy can reach the pixel level, providing a high-precision regional positioning basis for subsequent size calculation.

[0037] In step S4, perspective distortion is determined by detecting the pixel distribution features of the four edges of the paper. Specifically, the pixels of the four edges of the paper are extracted using an edge detection algorithm. Linear fitting is performed on the pixels of each edge to obtain the fitted line equations y=k1x+b1, y=k2x+b2, y=k3x+b3, and y=k4x+b4 (where k1 and k2 are the slopes of one pair of opposite edges, and k3 and k4 are the slopes of another pair of opposite edges). The difference in slopes between opposite edges, Δk1=|k1-k2| and Δk2=|k3-k4|, is calculated. If Δk1 or Δk2 exceeds a preset slope threshold (this threshold is set according to the image resolution and the allowable distortion error), then perspective distortion is determined to exist in the paper. This method can quickly and accurately identify perspective distortion, providing a basis for subsequent perspective correction and ensuring that correction is only performed when there is significant distortion, balancing detection accuracy and processing efficiency.

[0038] In step S1, the reference marker is a structural component of known size fixed inside the printer (such as a metal bracket or plastic clip inside the printer, whose dimensions are precisely measured and stored during equipment production), or a standard-sized object placed next to the paper (such as a standard credit card or a dedicated calibration block). The actual physical dimensions (such as length, width, and diameter) of the reference marker are pre-stored in the printer control system's storage module, using a standardized data format for easy retrieval during size conversion. The reference marker must meet the following requirements: stable material, not easily deformed; color significantly different from the paper and background for easy image segmentation; and fixed position to ensure complete inclusion in each image acquisition. By selecting appropriate reference markers, the accuracy and stability of the proportional conversion relationship can be improved, thereby ensuring the accuracy of paper size detection.

[0039] In step S9, the frequency of dynamic calibration is synchronized with the operating frequency of the printer's stepper motor. The operating frequency of the stepper motor is determined by the printing speed. Let the printing speed be v (unit: mm / s) and the feed distance per step of the stepper motor be SStep, then the operating frequency of the stepper motor is... (Unit: steps / s) The dynamic calibration frequency is consistent with f, meaning that a calibration process is performed once for every one step of motor operation. The preset number of steps can be adjusted according to the actual printing scenario. For example, for high-precision printing scenarios, calibration is performed once for every one step; for ordinary printing scenarios, calibration is performed once every 5-10 steps, balancing calibration accuracy and system computational load. Through dynamic calibration synchronized with the stepper motor's operating frequency, dimensional deviations generated during paper feeding can be corrected in real time, ensuring accurate matching between printed content and paper size and avoiding problems such as misaligned or missing prints.

[0040] The process also includes a paper type identification step, specifically: extracting the texture features and reflective properties of the paper in the image after preprocessing step S2 using the SegmentAnythingModel (SAM) visual large model. Texture feature extraction employs a gray-level co-occurrence matrix algorithm to calculate the gray-level co-occurrence matrix of the paper region at different directions and distances, extracting four feature parameters: energy, entropy, contrast, and correlation, to form the texture feature vector A1. Reflective property extraction analyzes the gray-level distribution histogram of the paper region, calculating three parameters: gray-level mean, gray-level variance, and peak gray-level value, to form the reflective property vector A2. The texture feature vector A1 and the reflective property vector A2 are concatenated to obtain the comprehensive paper feature vector A. The comprehensive feature vector A is then compared with a pre-set database of various paper features, which stores standard feature vectors Bi (i=1,2,...,n, where n is the number of paper types) for various types of paper, such as ordinary thermal paper, synthetic paper, label paper, and waterproof paper. The comparison employs a cosine similarity algorithm to calculate the similarity between the feature vector A of the paper to be identified and each standard feature vector Bi in the database. The similarity calculation formula is: cosθi=A⋅Bi / |A|×|Bi|, where A⋅Bi is the dot product of vectors A and Bi, and |A| and |Bi| are the magnitudes of vectors A and Bi, respectively. The paper type corresponding to the maximum similarity value max(cosθi) is selected as the identification result. If the maximum value is less than a preset similarity threshold, it is determined to be an unknown paper type, and the user is prompted for confirmation. Based on the identified paper type, the optimal print density and print speed parameters corresponding to that paper type are retrieved from the printer control system's parameter database and automatically sent to the printhead control module to achieve adaptive adjustment of print parameters. This step enables the printer to automatically adapt to different types of paper, ensuring clear and stable printing results on various types of paper, meeting the special printing needs of multiple industries such as retail, logistics, and medical, and improving the versatility and intelligence of the equipment.

[0041] In step S8, the printer's preset compatible size range is determined based on the device's hardware parameters, including the effective printing width range of the printhead [Wmin, Wmax], the maximum paper capacity length Lmax, and the minimum effective length Lmin. When the calculated actual paper width LW exceeds [Wmin, Wmax], or the actual paper height LH exceeds [Lmin, Lmax], the control system immediately triggers the abnormal handling process: pausing the printing task and cutting off the printhead drive signal; displaying abnormal information (such as "Paper width exceeds the compatible range, please replace with compliant paper") on the printer's built-in display screen, and simultaneously controlling the buzzer to issue an audible and visual alarm; if the printer is connected to an external device (such as a computer or POS system), sending an abnormal notification signal to the external device to remind the user to handle the issue promptly. This abnormal handling process ensures that the device will not malfunction due to paper size mismatch, extending the device's lifespan and reducing unnecessary maintenance costs.

[0042] In step S3, the activation condition for the backup detection mechanism is: in the segmentation mask output by the large visual model, the pixel proportion of the paper area or reference marker is lower than a preset threshold (e.g., the pixel proportion of the paper area is lower than 5% of the total pixels in the image), or the contour integrity of the segmentation mask is lower than a preset threshold (e.g., the missing part of the contour exceeds 10% of the total contour length). In the backup detection mechanism, the dual thresholds (high threshold TH and low threshold TL) of the Canny edge detection algorithm are determined by an adaptive method, i.e., TH=k1×mean(G), TL=k2×TH, where mean(G) is the average value of the image gradient magnitude, and k1 and k2 are preset coefficients (usually k1=0.2, k2=0.5). The contour extraction algorithm traverses the binarized image, marks the connected regions of all foreground pixels, calculates the area, perimeter, bounding rectangle, and other features of each connected region, compares them with preset features of paper and reference markers (e.g., area range, aspect ratio range), and filters out the target connected regions as the localization results of the paper area and reference markers. The backup detection mechanism provides dual protection for regional positioning, ensuring that target positioning can still be completed in complex environments (such as paper color being similar to the background and severe image noise), thereby improving the robustness and reliability of the system.

[0043] The embodiments of this application have been described above with reference to the accompanying drawings. Unless otherwise specified, the embodiments and features in the embodiments of this application can be combined with each other. This application is not limited to the specific embodiments described above. The specific embodiments described above are merely illustrative and not restrictive. Those skilled in the art can make many other forms under the guidance of this application without departing from the spirit and scope of the claims, and all of these forms are within the protection scope of this application.

Claims

1. A method for automatically detecting the height and width of a thermal printer paper based on a large model, characterized in that, Includes the following steps: S1. Image Acquisition: The thermal printer uses a built-in or external camera to capture images of the paper area inside the printer, ensuring that the image captures the entire paper area and preset reference markers. S2. Image preprocessing: Denoise, contrast enhancement and binarization are performed on the image acquired in step S1 to highlight the difference between the paper area and the background, and to provide clear image data for subsequent area detection. S3. Image Segmentation and Region Localization: The visual large model is called to segment the preprocessed image, obtain the segmentation mask of the paper area and reference markers, and accurately locate the specific position of the paper in the image. S4. Perspective Correction: For the paper area located in step S3, determine whether there is perspective distortion. If so, extract the four corner points of the paper and perform perspective transformation to obtain the front view of the paper. S5. Calculation of reference marker size: Based on the reference marker segmentation mask obtained in step S3, calculate the pixel size of the reference marker in the image; S6. Establish the proportional conversion relationship: Based on the known actual physical size of the reference marker and the pixel size calculated in step S5, establish the proportional conversion relationship between image pixels and actual physical size; S7. Paper pixel size acquisition: Based on the paper area located in step S3 and the front view obtained in step S4, calculate the pixel height and pixel width of the paper in the image. S8. Actual size conversion: Using the proportional conversion relationship established in step S6, convert the paper pixel height and pixel width obtained in step S7 into actual physical height and actual physical width; S9. Real-time calibration: During the printing process, repeat steps S1 to S8 to continuously acquire paper images and perform size detection, dynamically calibrate the actual height and width data of the paper to ensure detection accuracy; S10. Intelligent Early Warning: Based on the actual paper height data after calibration in step S9, combined with the paper length required for the printing task, the remaining paper usage is determined in real time. When the remaining usage is lower than the preset threshold, an early warning prompt is triggered.

2. The method of claim 1, wherein the method is based on a large model for automatic detection of the height and width of the thermal printer paper. In step S1, the camera is installed in a fixed position, and the acquisition angle is determined by pre-adjustment to ensure that the relative position of the reference marker and the paper remains stable in each acquired image.

3. The automatic detection method for the height and width of thermal printer paper based on a large model according to claim 1, characterized in that, In step S3, the large visual model is SegmentAnythingModel, which achieves accurate segmentation of the paper area and reference markers through zero-sample segmentation.

4. The automatic detection method for the height and width of thermal printer paper based on a large model according to claim 1, characterized in that, In step S4, perspective distortion is determined by detecting the pixel distribution characteristics of the four edges of the paper. When the edge pixel distribution is not parallel, perspective distortion is determined to exist.

5. The automatic detection method for the height and width of thermal printer paper based on a large model according to claim 1, characterized in that, In step S1, the reference marker is a known-sized structural component fixed inside the printer, or a standard-sized object placed next to the paper. The actual physical size of the reference marker is pre-stored in the printer control system.

6. The automatic detection method for the height and width of thermal printer paper based on a large model according to claim 1, characterized in that, In step S2, Gaussian filtering algorithm is used for image denoising, histogram equalization algorithm is used for contrast enhancement, and adaptive threshold segmentation algorithm is used for binarization.

7. The automatic detection method for the height and width of thermal printer paper based on a large model according to claim 1, characterized in that, In step S9, the frequency of dynamic calibration is synchronized with the operating frequency of the printer's stepper motor, and a calibration process is performed once every preset number of motor runs.

8. The automatic detection method for the height and width of thermal printer paper based on a large model according to claim 1, characterized in that, It also includes a paper type identification step, which is as follows: extract the texture features and reflective properties of the paper in the image after preprocessing in step S2 through a large visual model, compare it with a preset database of various paper features, determine the paper type, and automatically match the optimal printing density and printing speed parameters according to the paper type.

9. The automatic detection method for the height and width of thermal printer paper based on a large model according to claim 1, characterized in that, In step S8, when the calculated actual height and width of the paper exceed the printer's preset adaptation range, the printer control system issues an abnormality warning and suspends the printing task.

10. The automatic detection method for the height and width of thermal printer paper based on a large model according to claim 1, characterized in that, In step S3, if the visual large model segmentation fails to acquire the paper area or reference marker, the backup detection mechanism is activated. The paper area and reference marker are repositioned using edge detection algorithm and contour extraction algorithm before proceeding with the subsequent steps.