使用 Sobel 边缘检测方法时出错

问题描述

img = cv2.imread('skeleton.JPG')

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


sobelx = cv2.sobel(gray,cv2.CV_64F,1,ksize=5)
sobely = cv2.sobel(gray,ksize=5)

plt.imshow(cv2.cvtColor(sobelx,cv2.COLOR_BGR2RGB))

我收到如下错误

error                                     Traceback (most recent call last)
<ipython-input-51-3e640684ed0a> in <module>
----> 1 plt.imshow(cv2.cvtColor(sobelx,cv2.COLOR_BGR2RGB))

error: OpenCV(4.2.0) c:\projects\opencv-python\opencv\modules\imgproc\src\color.simd_helpers.hpp:94: error: (-2:Unspecified error) in function '__cdecl cv::impl::`anonymous-namespace'::CvtHelper<struct cv::impl::`anonymous namespace'::Set<1,-1,-1>,struct cv::impl::A0xe227985e::Set<3,4,struct cv::impl::A0xe227985e::Set<0,2,5>,2>::CvtHelper(const class cv::_InputArray &,const class cv::_OutputArray &,int)'
> Unsupported depth of input image:
>     'VDepth::contains(depth)'
> where
>     'depth' is 6 (CV_64F)

解决方法

在 Sobel 操作中,在计算 sobelxsobely 之后,您必须计算 np.sqrt(sobelx ** 2 + sobely ** 2)。之后,您应该选择一个阈值来查找边缘。此外,您将获得一张黑白图像,因此您无法将其转换为 RGB 或 BGR 图像。
正确的代码是:

import cv2
import matplotlib.pyplot as plt
import numpy as np

threshold = 6.

img = cv2.imread('skeleton.JPG')

gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) / 255

sobelx = cv2.Sobel(gray,cv2.CV_64F,1,ksize=5)
sobely = cv2.Sobel(gray,ksize=5)
sobel_xy = np.sqrt(sobelx ** 2 + sobely ** 2)
edge_image = np.float32(sobel_xy > threshold)

plt.imshow(edge_image,'gray')
plt.show()

如果您想显示 sobelx,您可以应用 np.abs 并将其标准化,然后显示:

sobelx_disp = np.abs(sobelx)
sobelx_disp = sobelx_disp / np.max(sobelx_disp)
plt.imshow(sobelx_disp,'gray')
plt.show()

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...