newbie - attempting object tracking / locating in opencv python, problems with findContours()

I'm attempting to locate a rectangular object by its color, and then find the coordinates of the center of the object, or the borders, I"m not picky about which.

I've been successful in isolating the color and creating a mask, but the findContours function is not working and i think it's because i've not successfully provided a proper bimodal image to findContours.

%matplotlib inline
import matplotlib.image as mpimg
from matplotlib import pyplot as plt
import cv2
import numpy as np

red_image = mpimg.imread('/vagrant/notebooks/red_thing.jpg')
hsv = cv2.cvtColor(red_image, cv2.COLOR_BGR2HSV)
lower_red = np.array([30,150,50])
upper_red = np.array([255,255,180])
mask = cv2.inRange(hsv, lower_red, upper_red)
res = cv2.bitwise_and(red_image,red_image, mask= mask)
kernel = np.ones((20,20),np.uint8)
ret,thresh1 = cv2.threshold(res,60,255,cv2.THRESH_BINARY)
# perform 'open' operation to homogenize object
opened = cv2.morphologyEx(thresh1, cv2.MORPH_OPEN, kernel)
image, contours, hierarchy = cv2.findContours(opened,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

The last line produces the following error, I can't figure out how to resolve this.

---------------------------------------------------------------------------
error                                     Traceback (most recent call last)
<ipython-input-130-06cc5691b64a> in <module>()
----> 1 image, contours, hierarchy = cv2.findContours(opened,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

error: /home/vagrant/opencv/modules/imgproc/src/contours.cpp:199: error: (-210) [Start]FindContours supports only CV_8UC1 images when mode != CV_RETR_FLOODFILL otherwise supports CV_32SC1 images only in function cvStartFindContours_Impl

1 answer

  • answered 2017-11-12 20:48 bethesdaboys

    i was able to fix the error with a conversion to gray, like this: gray = cv2.cvtColor(res, cv2.COLOR_BGR2GRAY)