使用 np.sqrt 处理图像后无法可视化图像



我正在尝试使用perwit内核进行边缘检测。

我的问题是当我试图";合并";水平梯度和垂直梯度,因为在它之后,我在cv2.imshow((函数中得到了一个错误,看起来图像有失真。

这是我的代码

imgx = filter_image(img,kx,3)
imgy = filter_image(img,ky,3)
img_edge = np.sqrt(np.power(imgx, 2) + np.power(imgy, 2))
img_edge = (img_edge / np.max(img_edge)) * 255
print(np.shape(img_edge))
print(np.min(img_edge))
print(np.max(img_edge))
cv2.imshow('imagey',img_edge)

这是我的输出

(256, 256)
0.0
255.0
Traceback (most recent call last):
File "<ipython-input-17-c200db56adba>", line 1, in <module>
runfile('C:/Users/giorg/Desktop/Elte/Image Analysis/Lab 1/filter.py', wdir='C:/Users/giorg/Desktop/Elte/Image Analysis/Lab 1')
File "C:UsersgiorgAnaconda3libsite-packagesspyder_kernelscustomizespydercustomize.py", line 827, in runfile
execfile(filename, namespace)
File "C:UsersgiorgAnaconda3libsite-packagesspyder_kernelscustomizespydercustomize.py", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/giorg/Desktop/Elte/Image Analysis/Lab 1/filter.py", line 58, in <module>
cv2.imshow('imagey',img_edge)
TypeError: Expected Ptr<cv::UMat> for argument 'mat'

我不知道为什么,但我认为问题是np.sqrt((。如果我对imgy和imgx进行简单的求和,它就可以了。

问题是,您传入的是np.float64的数组,而不是openCV能够理解的类型,例如np.unit8。具体来说,sqrt之后的步骤映射到正确的范围,但不调整类型:

img_edge = (img_edge / np.max(img_edge)) * 255

您可以判断,因为最小/最大打印输出中有一个小数点,这通常只在打印浮点类型时发生。

再增加一个步骤:

cv2.imshow('imagey', img_edge.astype(np.uint8))

或者单独操作:

img_edge = img_edge.astype(np.uint8)