While preparing this answer, I realized, that my hint regarding cv2.boxPoints
was misleading. Of course, I had cv2.boundingRect
on my mind – sorry for that!
Nevertheless, here's the full step-by-step approach:
- Use
cv2.inRange
to mask all yellow pixels. Attention: Your image has JPG artifacts, such that you get a lot of noise in the mask, cf. the output:
Use cv2.findContours
to find all contours in the mask. That'll be over 50, due to the many tiny artifacts.
Use Python's max
function on the (list of) found contours using cv2.contourArea
as key to get the largest contour.
Finally, use cv2.boundingRect
to get the bounding rectangle of the contour. That's a tuple (x, y, widht, height)
. Just use the last two elements, and you have your desired information.
That'd be my code:
import cv2
# Read image with OpenCV
img = cv2.imread('path/to/your/image.ext')
# Mask yellow color (0, 255, 255) in image; Attention: OpenCV uses BGR ordering
yellow_mask = cv2.inRange(img, (0, 255, 255), (0, 255, 255))
# Find contours in yellow mask w.r.t the OpenCV version
cnts = cv2.findContours(yellow_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
# Get the largest contour
cnt = max(cnts, key=cv2.contourArea)
# Get width and height from bounding rectangle of largest contour
(x, y, w, h) = cv2.boundingRect(cnt)
print('Width:', w, '| Height:', h)
The output
Width: 518 | Height: 320
seems reasonable.
----------------------------------------
System information
----------------------------------------
Platform: Windows-10-10.0.16299-SP0
Python: 3.8.5
OpenCV: 4.5.1
----------------------------------------
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…