0
votes

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 ?

1

1 Answers

1
votes

You need a way to convert a measurement in pixels to one in meters. Possible ways to do that are, in order of accuracy.

  • Look up the physical dimensions of the camera sensors, e.g. from the spec sheet of the camera or, if you are lucky, from the metadata stored in the image along with the pixels (EXIF header)
  • Place an object of known size in the scene.
  • Directly scale the focal length from pixels to mm as given by the lens.