在python中运行Basic OpenCV程序

时间:2019-02-12 06:15:01

标签: python-3.x opencv anaconda

我是一个尝试学习opencv的初学者。我已经在ubuntu系统中成功安装了opencv,并试图从Internet运行一些代码,但是遇到了这个问题

# import the necessary packages
from __future__ import print_function
import imutils
import cv2

# load the Tetris block image, convert it to grayscale, and threshold
# the image
print("OpenCV Version: {}".format(cv2.__version__))
image = cv2.imread("tetris_blocks.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 225, 255, cv2.THRESH_BINARY_INV)[1]

# check to see if we are using OpenCV 2.X or OpenCV 4
if imutils.is_cv2() or imutils.is_cv4():
    (cnts, _) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
        cv2.CHAIN_APPROX_SIMPLE)

# check to see if we are using OpenCV 3
elif imutils.is_cv3():
    (_, cnts, _) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
        cv2.CHAIN_APPROX_SIMPLE)

# draw the contours on the image
cv2.drawContours(image, cnts, -1, (240, 0, 159), 3)
cv2.imshow("Image", image)
cv2.waitKey(0)

输出应为图像,但出现以下错误:

runfile('/home/viper_36/pythontemp/temp.py', wdir='/home/viper_36/pythontemp')
OpenCV Version: 4.0.0
Traceback (most recent call last):

  File "<ipython-input-1-202e5c8bcd5b>", line 1, in <module>
    runfile('/home/viper_36/pythontemp/temp.py', wdir='/home/viper_36/pythontemp')

  File "/home/viper_36/anaconda3/lib/python3.6/site-packages/spyder_kernels/customize/spydercustomize.py", line 704, in runfile
    execfile(filename, namespace)

  File "/home/viper_36/anaconda3/lib/python3.6/site-packages/spyder_kernels/customize/spydercustomize.py", line 108, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "/home/viper_36/pythontemp/temp.py", line 11, in <module>
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

error: OpenCV(4.0.0) /io/opencv/modules/imgproc/src/color.cpp:181: error: (-215:Assertion failed) !_src.empty() in function 'cvtColor'

1 个答案:

答案 0 :(得分:0)

错误的最后一行: (-215:Assertion failed) !_src.empty() in function 'cvtColor' 告诉你很多!

“断言”表示软件正在检查某些内容:“如果接下来出现的内容不正确:我将抛出错误。” 接下来的!_src.empty()可以翻译为:“源图像不为空”。这必须为真,否则断言将引发错误。

这全部意味着您提供的图像路径不在图像所在的位置。确保俄罗斯方块图像与您要执行的图像位于同一文件夹中。 或使用绝对路径。在Ubuntu中,其外观应类似于/home/<user>/path/to/image/tetris_blocks.png 如果您在文件浏览器中按ctrl-c映像,则将复制绝对路径!