'Measure object width for rotated and noisy objects
I want to measure an object width (in pixels).
Here are three representative examples of the images I have (they come from an object detector):
First one is easy, the bounding box is practically giving me the width already.
Second one is a bit rotated.
Third one is rotated and also has a little peak around the middle, which is to be ignored for width measurement.
Fourth one has the peak, and also parts of other nearby objects.
So far I have done thresholding and closing with a rectangular and tall kernel to find the straight vertical part of the object. Which works good except with the rotated objects, and also does not get rid of the neighboring object parts. Here are some samples:
Now how would I find the line that goes along the right of my object? I can only imagine how to do it for the non-rotated objects (using the contour bounding rectangles, see green line)
My guess is that I need to find the angle of the long line and rotate the image, since my method seems to be working good for aligned objects.
In case it is not clear, here is an example of the width I want to measure (distance between two red lines, or average distance in case they are not parallel):
Code so far:
ret, crop = cv2.threshold(crop, 120, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
closeKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,90))
close = cv2.morphologyEx(crop, cv2.MORPH_CLOSE, closeKernel)
cnts = cv2.findContours(~close, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]
right_limit = 0
for c in cnts:
(x, y, w, h) = cv2.boundingRect(c)
if h > .3*H: # To filter out parts of other objects
right_limit = max(right_limit, x + w)
crop = cv2.cvtColor(crop, cv2.COLOR_GRAY2BGR)
cv2.line(crop, (right_limit, 0), (right_limit, H), (0, 255, 0), thickness=2)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|






