OpenCV示例不工作阈值?

时间:2018-02-14 16:26:57

标签: python opencv

我正在尝试从opencv网站执行这段代码: https://docs.opencv.org/3.4.0/d7/d4d/tutorial_py_thresholding.html

import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img = cv.imread('gradient.png',0)
ret,thresh1 = cv.threshold(img,127,255,cv.THRESH_BINARY)
ret,thresh2 = cv.threshold(img,127,255,cv.THRESH_BINARY_INV)
ret,thresh3 = cv.threshold(img,127,255,cv.THRESH_TRUNC)
ret,thresh4 = cv.threshold(img,127,255,cv.THRESH_TOZERO)
ret,thresh5 = cv.threshold(img,127,255,cv.THRESH_TOZERO_INV)
titles = ['Original Image','BINARY','BINARY_INV','TRUNC','TOZERO','TOZERO_INV']
images = [img, thresh1, thresh2, thresh3, thresh4, thresh5]
for i in xrange(6):
    plt.subplot(2,3,i+1),plt.imshow(images[i],'gray')
    plt.title(titles[i])
    plt.xticks([]),plt.yticks([])
plt.show()

它给了我以下错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-5-8bba9576502d> in <module>()
     11 images = [img, thresh1, thresh2, thresh3, thresh4, thresh5]
     12 for i in xrange(6):
---> 13     plt.subplot(2,3,i+1),plt.imshow(images[i],'gray')
     14     plt.title(titles[i])
     15     plt.xticks([]),plt.yticks([])

/usr/lib/pymodules/python2.7/matplotlib/pyplot.pyc in imshow(X, cmap, norm, aspect, interpolation, alpha, vmin, vmax, origin, extent, shape, filternorm, filterrad, imlim, resample, url, hold, **kwargs)
   2890                         vmax=vmax, origin=origin, extent=extent, shape=shape,
   2891                         filternorm=filternorm, filterrad=filterrad,
-> 2892                         imlim=imlim, resample=resample, url=url, **kwargs)
   2893         draw_if_interactive()
   2894     finally:

/usr/lib/pymodules/python2.7/matplotlib/axes.pyc in imshow(self, X, cmap, norm, aspect, interpolation, alpha, vmin, vmax, origin, extent, shape, filternorm, filterrad, imlim, resample, url, **kwargs)
   7298                        filterrad=filterrad, resample=resample, **kwargs)
   7299 
-> 7300         im.set_data(X)
   7301         im.set_alpha(alpha)
   7302         self._set_artist_props(im)

/usr/lib/pymodules/python2.7/matplotlib/image.pyc in set_data(self, A)
    423         if (self._A.dtype != np.uint8 and
    424             not np.can_cast(self._A.dtype, np.float)):
--> 425             raise TypeError("Image data can not convert to float")
    426 
    427         if (self._A.ndim not in (2, 3) or

TypeError: Image data can not convert to float

我甚至尝试使用plt.imshow(thresh1)打印图像,即使这也会产生同样的错误。

Opencv版本为'2.4.8',python版本为2.7.6 但为什么演示不起作用呢?

0 个答案:

没有答案