获取错误OpenCV(3.4.1)C:\projects\OpenCV python\OpenCV\modules\imgproc\src\thresh.cpp:1406:错误:(-215)

2024-04-26 23:18:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我运行了下面的代码,得到一个错误

OpenCV(3.4.1) C:\projects\opencv-python\opencv\modules\imgproc\src\thresh.cpp:1406: error: (-215) src.type() == (((0) & ((1 << 3) - 1)) + (((1)-1) << 3)) in function cv::threshold

我不清楚这意味着什么以及如何解决

import numpy as numpy
from matplotlib import pyplot as matplot
import pandas as pandas
import math
from sklearn import preprocessing
from sklearn import svm
import cv2

blur = cv2.GaussianBlur(img,(5,5),0)
ret3,th3 = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
image = numpy.invert(th3)
matplot.imshow(image,'gray')
matplot.show()

Tags: fromimageimportsrcnumpypandasthresholdas
1条回答
网友
1楼 · 发布于 2024-04-26 23:18:40

您将能够用以下方法解决您的错误。

首先检查输入图像是否只有一个通道。您可以通过运行print img.shape来检查它。如果结果类似于(height, width, 3),则图像不是单通道。可以通过以下方法将图像逐个转换为单个通道:

img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

然后检查图像类型是否不是float。您可以通过运行print img.dtype来检查它。如果结果与float相关,则还需要通过以下方式进行更改:

img = img.astype('uint8')

最后一点,在这种情况下,这并不是一个错误。但如果你继续练习这种组合多个标志的方法,将来可能会出错。当您使用多个标志时,请记住不要使用加号,而应使用

 ret3,th3 = cv2.threshold(blur,0,255,cv2.THRESH_BINARY | cv2.THRESH_OTSU)

最后,可以使用opencv函数来显示图像。不需要依赖其他库。

最终代码如下:

img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img = img.astype('uint8')
blur = cv2.GaussianBlur(img,(5,5),0)
ret3,th3 = cv2.threshold(blur,0,255,cv2.THRESH_BINARY | cv2.THRESH_OTSU)
image = numpy.invert(th3)
cv2.show('image_out', image)
cv2.waitKey(0)
cv2.destroyAllWindows() 

相关问题 更多 >