I have written a code in opencv-python for calculating the number of pixels in height and width of an object. Lets say,
height = 567 pixels width = 324 pixels I also have KNOWN_FOCAL_LENGTH of camera and distance between the original object and camera.
# Getting the biggest contour
cnt = max(contours, key = cv2.contourArea)
cv2.drawContours(image, cnt, -1, (0, 255, 0), 3)
peri = cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, 0.005* peri, True)
# get the bounding rect
x, y, w, h = cv2.boundingRect(approx)
print("Width in pixels : {}, Height in pixels : {}".format(w,h))
# draw a green rectangle to visualize the bounding rect
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
WidthData = "Width : {} mm".format(round(w/scaling_factor,2))
HeightData = "Height : {} mm".format(round(h/scaling_factor,2))
textData = WidthData + ", " + HeightData
cv2.putText(image, textData, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 0), 2)
print(WidthData)
print(HeightData)
cv2.imshow('Result', image)
How can I calculate the factor with which I can convert my number_of_pixels to original_length of image ? How to calculate scaling_factor ?