Finding out length of the line in pixel

Hello,
i


'm seeking guidance on determining the length of a line in pixels within an image using OpenCV or similar libraries. Despite attempting code for this task, the pixel count obtained seems inaccurate. I also have labeled data provided by a lab technician, which I aim to utilize for validation. Could someone advise on how to improve this process?

below is the code

    hsv = cv2.cvtColor(image_path, cv2.COLOR_BGR2HSV)
    lower = np.array([50, 100, 100]) 
    upper = np.array([70, 255, 255]) 

    # Create a mask for detecting green color
    mask = cv2.inRange(hsv, lower, upper)
    # Find contours in the mask
    contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    max_contour = max(contours)

    green_line_image = original_image.copy()
    cv2.drawContours(green_line_image, [max_contour], -1, (0, 255, 0), 1)

    green_line_length = cv2.arcLength(max_contour, closed=False)

    print(green_line_length)

Wouldn’t findContours give you s rectangle aroud the line, arc of which would be “inaccurate”… You should use a line detection function, such as HoughLines

try to get the width of the contour’s bbox:

r = cv2.boundingRect(max_contour)
w = r[2] # r = [x,y,w,h]