Hello,
I am trying to track an object in an image, using examples that I have found in opencv documention as well as from other users, and right now I am able to use drawCounters but cannot use boundingRect, instead of selecting just the object, it selects the whole image.
Here is the source image:
Here is the result image with drawContours and the failed boundingRect:
This is the code that I am using:
import numpy as np
import cv2
img = cv2.imread('20180801_172750_Film2.jpg')
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_blur = cv2.GaussianBlur(img_gray,(5,5),0)
img_bgr = cv2.cvtColor(img_blur,cv2.COLOR_GRAY2BGR)
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
#### Object Tracking A
# define range of color in HSV
lowHue = 0
lowSat = 0
lowVal = 135
highHue = 255
highSat = 55
highVal = 255
# creation of mask
colorLow = np.array([lowHue,lowSat,lowVal])
colorHigh = np.array([highHue,highSat,highVal])
img_mask = cv2.inRange(img_hsv, colorLow, colorHigh)
# find and draw contours
#find
im2, contours, hierarchy = cv2.findContours(img_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
#draw
cv2.drawContours(img, contours, -1, (0,255,0), 3)
#find largest contour
contour_sizes = [(cv2.contourArea(contour), contour) for contour in contours]
#print (contour_sizes)
biggest_contour = max(contour_sizes, key=lambda x: x[0])[1]
# bounding rectangle
x,y,w,h = cv2.boundingRect(biggest_contour)
print ('rectangle size: x=%s y=%s w=%s h=%s' %(x,y,w,h))
img_rect = cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
####
cv2.imshow('img',img)
#cv2.imshow('img_gray',img_gray)
#cv2.imshow('img_blur',img_blur)
#cv2.imshow('img_bgr',img_bgr)
#cv2.imshow('img_hsv',img_hsv)
cv2.imshow('img_mask',img_mask)
cv2.waitKey(0)
cv2.destroyAllWindows()