【问题标题】:Distance Transform in OpenCV Python automatically converting CV_8UC3 to CV_32SC1 creating an assertion errorOpenCV Python中的距离变换自动将CV_8UC3转换为CV_32SC1,创建一个断言错误
【发布时间】:2016-11-09 12:55:14
【问题描述】:

我正在尝试按照教程将分水岭算法应用于图像:OpenCv WaterShed Docs。我之前在灰度图像上应用了高斯滤波和形态变换后的 Otsu 阈值处理,以根据代码提高图像质量:

img = cv2.imread('Results\Feb_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 位单通道图像。如何防止这种情况发生,同时使用距离变换?

【问题讨论】:

  • 你能解决吗?
  • 很遗憾我没能解决
  • 我似乎根本没有收到此错误。你能上传你正在使用的图片吗?
  • 此外,使用 1 的内核大小进行卷积不会改变任何内容。尝试将内核大小更改为 3 或更大

标签: python opencv computer-vision opencv3.0 watershed


【解决方案1】:

当您输入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 中测试的。

【讨论】:

    【解决方案2】:

    在函数cv2.watershed(img,markers) 中,您的输入参数img 必须有3 个通道。 完整的工作代码:

    #Load image in grayscale
    img = cv2.imread('Results\Feb_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('Results\Feb_16-0.jpg',1)
    
    markers = cv2.watershed(img,markers)
    img[markers == -1] = [255,0,0]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-25
      • 1970-01-01
      • 2013-02-26
      • 2014-04-29
      相关资源
      最近更新 更多