我正在尝试按照教程将WaterShed算法应用于图像:OpenCv WaterShed Docs 。我之前在灰度图像上应用了高斯滤波和形态变换后的 Otsu 阈值,以按照代码提高图像质量:
img = cv2.imread('ResultsFeb_16-0.jpg',0)
kernel = np.ones((1,1),np.uint8)
opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
blur = cv2.GaussianBlur(opening,(1,1),0)
ret3,th4 = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
根据代码将距离变换作为分水岭算法的第一阶段:
# sure background area
sure_bg = cv2.dilate(opening,kernel,iterations=1)
# Finding sure foreground area
dist_transform = cv2.distanceTransform(opening,cv2.DIST_L2,3)
创建错误:
error: (-215) src.type() == CV_8UC3 && dst.type() == CV_32SC1 in function cv::watershed
其中,8位3通道图像被尝试转换为32位单通道图像。如何防止这种情况,同时使用距离变换?
当您输入数组到 cv2.distanceTransform
中的数组格式不正确时,会出现此错误。它应该是 np.uint8(不是 int8)类型的二维数组。
例如
import cv2 as cv
import numpy as np
testim = np.zeros((11,11), dtype = uint8)
testim[2:6,1:6] = 255
testim[3,3] = 0
print(testim)
dist = cv.distanceTransform(testim, cv.DIST_L2, 5)
print(testim)
如果您正在读取格式不正确的图像,则必须首先将其转换为灰色(只有一个通道),并确保它是uint8格式。这可以通过imagename.astype(np.uint8)
来完成
这在opencv版本3.3.1,python 3.5中进行了测试。
在函数cv2.watershed(img,markers)
输入参数中,img
必须有 3 个通道。完整工作代码:
#Load image in grayscale
img = cv2.imread('ResultsFeb_16-0.jpg',0)
kernel = np.ones((1,1),np.uint8)
opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
blur = cv2.GaussianBlur(opening,(1,1),0)
ret3,th4 = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
# sure background area
sure_bg = cv2.dilate(opening,kernel,iterations=1)
# Finding sure foreground area
dist_transform = cv2.distanceTransform(opening,cv2.DIST_L2,3)
ret, sure_fg = cv2.threshold(dist_transform,0.7*dist_transform.max(),255,0)
sure_fg = np.uint8(sure_fg)
unknown = cv2.subtract(sure_bg,sure_fg)
ret, markers = cv2.connectedComponents(sure_fg)
markers = markers+1
markers[unknown==255] = 0
markers = markers.astype('int32')
#now load same image as color image
img = cv2.imread('ResultsFeb_16-0.jpg',1)
markers = cv2.watershed(img,markers)
img[markers == -1] = [255,0,0]