1

I am trying to preform image processing techniques such as histogram backprojection and morphological filtering, but whenever I try to find a contour on the processed image, it keeps giving me an error:

line 66, in <module>
    contours, hierarchy = cv2.findContours(thresh.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
error: /build/buildd/opencv-2.4.8+dfsg1/modules/imgproc/src/contours.cpp:196: error: (-210) [Start]FindContours support only 8uC1 and 32sC1 images in function cvStartFindContours

I tried to find multiple ways to convert my processed image into either a 8uC1 or 32sC1, but have failed. Can anyone tell me how do I convert the image into a type 8uC1 or type 32sC1 so that I can find contours within the image?

Code:

import cv2
import numpy as np
from pyimagesearch import imutils
from PIL import Image

def invert_img(img):
    img = (255-img)
    return img

roi = cv2.imread('images/surgeon_2.jpg')

hsv = cv2.cvtColor(roi,cv2.COLOR_BGR2HSV)

target = cv2.imread('images/surgeon_2.jpg')

hsvt = cv2.cvtColor(target,cv2.COLOR_BGR2HSV)

img_height = target.shape[0]
img_width = target.shape[1]

# calculating object histogram
roihist = cv2.calcHist([hsv],[0, 1], None, [180, 256], [0, 180, 0, 256] )

# normalize histogram and apply backprojection
cv2.normalize(roihist,roihist,0,255,cv2.NORM_MINMAX)
dst = cv2.calcBackProject([hsvt],[0,1],roihist,[0,180,0,256],1)

# Now convolute with circular disc
disc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
cv2.filter2D(dst,-1,disc,dst)

# threshold and binary AND
ret,thresh = cv2.threshold(dst,50,255,0)
thresh = cv2.merge((thresh,thresh,thresh))
res = cv2.bitwise_and(target,thresh)

# Showing before morph
thresh_c = thresh.copy()
img_c = np.vstack((target,thresh_c,res))
img_c = imutils.resize(img_c, height = 700)
cv2.imshow('Before morph', thresh_c)


# Implementing morphological erosion & dilation
kernel = np.ones((9,9),np.uint8)
thresh = cv2.erode(thresh, kernel, iterations = 1)
thresh = cv2.dilate(thresh, kernel, iterations=1)


# Invert the image
thresh = invert_img(thresh)


res = np.vstack((target,thresh,res))
#cv2.imwrite('res.jpg',res)
res = imutils.resize(res, height = 700)
cv2.imshow('After morph', res)
cv2.waitKey(0)


# Code to draw the contours
contours, hierarchy = cv2.findContours(thresh.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cnts = sorted(contours, key = cv2.contourArea, reverse = True)[:5]
cv2.drawContours(thresh.copy(), cnts, -1,(0,255,0),2)
cv2.imshow('All contours', thresh)
cv2.waitKey(0)
4

1 回答 1

-1
###findContours function works on GRAYSCALE (monochrome) image.
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (5, 5), 0)
thresh = gray 
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,  
cv2.CHAIN_APPROX_SIMPLE)
于 2017-10-10T08:06:50.077 回答