我只是在学习图像处理,但是cvtColor功能无法正常工作。它显示以下错误。

OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file /build/opencv-SviWsf/opencv-2.4.9.1+dfsg/modules/imgproc/src/color.cpp, line 3737
Traceback (most recent call last):
  File "harriscorner.py", line 6, in <module>
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cv2.error: /build/opencv-SviWsf/opencv-2.4.9.1+dfsg/modules/imgproc/src/color.cpp:3737: error: (-215) scn == 3 || scn == 4 in function cvtColor

实际上,我正在尝试harris拐角检测方法,但cvtColor fucion无法正常工作。任何人的帮助将不胜感激。
这是我的代码。
import cv2
import numpy as np

filename = 'chessboard.jpg'
img = cv2.imread(filename)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

gray = np.float32(gray)
dst = cv2.cornerHarris(gray,2,3,0.04)

#result is dilated for marking the corners, not important
dst = cv2.dilate(dst,None)

# Threshold for an optimal value, it may vary depending on the image.
img[dst>0.01*dst.max()]=[0,0,255]

cv2.imshow('dst',img)
if cv2.waitKey(0) & 0xff == 27:
    cv2.destroyAllWindows()

最佳答案

由于您的代码从文件读取后的第一个cvtColor处显示错误,因此读取操作很可能失败。

首先,请确保正确读取图像:

filename = 'chessboard.jpg'
img = cv2.imread(filename)
cv2.imshow("src",img)
cv2.waitKey(0)#proceed to remaining code when you press a key
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

如果在此显示中看不到图像,请检查filePath是否正确。

07-27 19:29