Skip to main content
. 2025 Dec 12;18(24):5579. doi: 10.3390/ma18245579
Algorithm 1. Automated Scale Bar Detection
Input: grayscale or RGB image P after preprocessing
Output: scale ratio R = Lphys/Lpx, real-world dimensions of image Wreal, Hreal
1: Image ← convert P to RGB if grayscale;
2: (Hpx, Wpx) ← Image.shape;
3: ROI  Image[Hpx//2:, :];//Define ROI as the lower half of P
4: HSV ← Convert ROI to HSV color space;
5: mask ← inRange(hsv, lower = (0, 0, 0), upper = (180, 255, 30));//Create black mask using HSV thresholds
6: contours ← findContours(mask);//Extract contours from the mask
7: Initialize Lpx ← 0;
8: for each contour do
9:  edge_img ← Canny(drawFilledContour(mask.shape, contour), 50, 150);//Apply Canny edge detection
//Use probabilistic Hough transform to detect lines
10:  lines ← HoughLinesP(edge_img, rho = 1, theta = π/180, threshold = 50,
        minLineLength = 50, maxLineGap = 10);
11: for each detected line (x1, y1), (x2, y2) do
12:   Compute length l=x2x12+y2y12;
13:   if l>Lpx then
14:    Lpxl;//Update Lpx
15: Lphys ← CnOCR_detect_numeric_value(ROI);
16: if Lphys = None then
17: Lphys ← ask_user_input(“Please enter the actual length of scale bar (µm):”);//Prompt user to input physical length Lphys
18: R  Lphys/Lpx;//Compute scale ratio R
19: Wreal  Wpx·R;//Compute real-world width of image
20: Hreal  Hpx·R;//Compute real-world height of image
21: Return R, Wreal, Hreal;