我正在尝试执行图像处理技术,例如直方图反投影和形态过滤,但是每当我尝试在处理后的图像上找到轮廓时,它总是给我一个错误:

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

我试图找到多种方法将经过处理的图像转换为8uC1或32sC1,但是失败了。谁能告诉我如何将图像转换为8uC1类型或32sC1类型,以便可以在图像中找到轮廓?

码:
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)

最佳答案

###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)

07-26 08:04