【已解决】pycharm + opencv 常见报错:(-215:Assertion failed)_src.empty() in function ‘cv::cvtColor‘

用pycharm运行opencv的一个程序,结果显示窗口不能正常显示图像,这个效果:

【已解决】pycharm + opencv 常见报错:(-215:Assertion failed)_src.empty() in function ‘cv::cvtColor‘_第1张图片

报错如下:

Traceback (most recent call last):
  File "D:\Users\l\anaconda3\envs\justdoit\lib\site-packages\IPython\core\interactiveshell.py", line 3457, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "", line 1, in 
    runfile('E:/01-Python_In_One/Project/S2D_Daily/test/testOpenCV.py', wdir='E:/01-Python_In_One/Project/S2D_Daily/test')
  File "D:\Program Files\JetBrains\PyCharm 2021.2.2\plugins\python\helpers\pydev\_pydev_bundle\pydev_umd.py", line 198, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "D:\Program Files\JetBrains\PyCharm 2021.2.2\plugins\python\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "E:/01-Python_In_One/Project/S2D_Daily/test/testOpenCV.py", line 11, in 
    cv2.imshow('origin', image)
cv2.error: OpenCV(4.5.4) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: **(-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'**

原因:

imread的时候,读取的路径错了,有两种情况,上述的215是因为路径不对,还有一种182错误,是因为路径中有中文字符。

报错场景:

【已解决】pycharm + opencv 常见报错:(-215:Assertion failed)_src.empty() in function ‘cv::cvtColor‘_第2张图片

代码如下:

import cv2

image = cv2.imread('./test/building.jpg', cv2.IMREAD_GRAYSCALE)
cv2.imshow('origin', image)

h, w = image.shape  # 获取图像的高度和宽度

# Sobel 滤波器 进行边的检测
sobel_horizontal = cv2.Sobel(image, cv2.CV_64F, 1, 0, ksize=5)  # 水平方向
sobel_vetical = cv2.Sobel(image, cv2.CV_64F, 0, 1, ksize=5)  # 垂直方向
cv2.imshow('sobel_H', sobel_horizontal)  # 水平方向
cv2.imshow('sobel_V', sobel_vetical)  # 垂直方向

# 拉普拉斯算子 进行边的检测    64F代表每一个像素点元素占64位浮点数
laplacian = cv2.Laplacian(image, cv2.CV_64F, ksize=5)
cv2.imshow('laplacian', laplacian)

# # Canny边检测器
canny = cv2.Canny(image, 50, 240)
cv2.imshow('Canny', canny)

cv2.waitKey(0)
cv2.destroyAllWindows()

修改正确的代码:

仅仅上述第10行有修正:

image = cv2.imread('building.jpg', cv2.IMREAD_GRAYSCALE)

对应文件夹,查看路径。这里困扰了很久路径应该怎么设置。

你可能感兴趣的:(Debug,Python/Pycharm,图像处理,opencv,pycharm,python)