使用numpy后Opencv Otsu Thresholding错误?

Sar*_*oon 0 python opencv numpy

在我的帖子中,我将python迭代循环优化为numpy方式.

然后我面临下一个问题,将其转换为二进制图像

def convertRed(rawimg):
    blue = rawimg[:,:,0]
    green = rawimg[:,:,1]
    red = rawimg[:,:,2]
    exg = 1.5*red-green-blue
    processedimg = np.where(exg > 50, exg, 2)
    ret2,th2 = cv2.threshold(processedimg,0,255,cv2.THRESH_OTSU) //error line

    return processedimg
Run Code Online (Sandbox Code Playgroud)

错误在这里

错误:(-215)src.type()== CV_8UC1在函数cv :: threshold中

如何解决这个问题呢?

Eli*_*art 5

cv2.threshold函数仅接受uint8值,这意味着如果图像中的像素值介于0和255之间,则只能应用Otsu算法.

正如您所看到的,当您将值乘以1.5图像时,开始显示浮点值,使您的图像不适合cv2.threshold,因此您的错误消息为src.type()== CV_8UC1.

您可以修改代码的以下部分:

processedimg = np.where(exg > 50, exg, 2)
processedimg = cv2.convertScaleAbs(processedimg)
ret2,th2 = cv2.threshold(processedimg,0,255,cv2.THRESH_OTSU) //error line
Run Code Online (Sandbox Code Playgroud)

我们在这里做的是使用OpenCV函数cv2.convertScaleAbs,您可以在OpenCV文档中看到:

cv2. convertScaleAbs
Run Code Online (Sandbox Code Playgroud)

缩放,计算绝对值,并将结果转换为8位.

Python:cv2.convertScaleAbs(src [,dst [,alpha [,beta]]])→dst