Ask Your Question
0

[SOLVED] boundingRect selects all image instead of target object

asked 2018-08-10 04:16:54 -0500

marafado88 gravatar image

updated 2018-08-10 05:30:47 -0500

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 drawContours but cannot use boundingRect, instead of selecting just the object, it selects the whole image.

Here is the source image:

image description

Here is the result image with drawContours and the failed boundingRect:

image description

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()
edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
0

answered 2018-08-10 05:34:42 -0500

marafado88 gravatar image

updated 2018-08-10 05:56:37 -0500

In line findContours I had to change img_mask to ~img_mask, to invert colors, since white is the target color for boundingRect,

im2, contours, hierarchy = 
     cv2.findContours(~img_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

image description

Thanks for the help mcclintic_!!

edit flag offensive delete link more
Login/Signup to Answer

Question Tools

1 follower

Stats

Asked: 2018-08-10 04:16:54 -0500

Seen: 31 times

Last updated: Aug 10