I have this image with 3 channels RGB (a result of a VARI Index computation) and I would like to draw bounding boxes (rectangles) around the plants, represented in green here. What is the best and easiest way to do it with OpenCV / python?
I guess it’s an easy problem for OpenCV experts, but I could not find good tutorials online to do this for multiple objects.
The closest tutorial I found was: determining-object-color-with-opencv
The assumptions for the bounding boxes should/could be:
- green is the dominant color.
- it should be more than X pixels.
Thanks in advance!
Advertisement
Answer
Just answering my own question after stumbling upon this resource: https://docs.opencv.org/3.4/da/d0c/tutorial_bounding_rects_circles.html
May not be the best answer but it somehow solves my problem!
JavaScript
x
34
34
1
import cv2
2
import numpy as np
3
4
image = cv2.imread('vari3.png')
5
6
# https://www.pyimagesearch.com/2016/02/15/determining-object-color-with-opencv/
7
# https://docs.opencv.org/3.4/da/d0c/tutorial_bounding_rects_circles.html
8
9
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
10
lab = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)
11
12
# mask: green is dominant.
13
thresh = np.array((image.argmax(axis=-1) == 1) * 255, dtype=np.uint8)
14
15
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]
16
17
contours_poly = [None] * len(cnts)
18
boundRect = [None] * len(cnts)
19
for i, c in enumerate(cnts):
20
contours_poly[i] = cv2.approxPolyDP(c, 3, True)
21
boundRect[i] = cv2.boundingRect(contours_poly[i])
22
23
for i in range(len(cnts)):
24
# cv2.drawContours(image, contours_poly, i, (0, 255, 0), thickness=2)
25
pt1 = (int(boundRect[i][0]), int(boundRect[i][1]))
26
pt2 = (int(boundRect[i][0] + boundRect[i][2]), int(boundRect[i][1] + boundRect[i][3]))
27
if np.sqrt((pt2[1] - pt1[1]) * (pt2[0] - pt1[0])) < 30:
28
continue
29
cv2.rectangle(image, pt1, pt2, (0, 0, 0), 2)
30
31
cv2.imwrite('result.png', image)
32
cv2.imshow("Image", image)
33
cv2.waitKey(0)
34