【问题标题】:Assertion failed (m.dims >= 2) in MatMat 中的断言失败(m.dims >= 2)
【发布时间】:2016-03-25 11:15:55
【问题描述】:

这是图像阈值处理的代码,我在第 22 行遇到错误,

这是:-

ret,thresh2 = cv2.threshold(img,127,255,cv2.THRESH_BINARY_INV)

在此代码中,我想从摄像机捕获图像帧,然后对捕获的图像帧执行各种阈值操作。

我存储了不同时间实例的图像帧。我的目标是分割视频中的移动物体。因此,我正在应用阈值操作。

有人知道怎么做吗?

提前致谢。

import cv2
import numpy as np
import time
from matplotlib import pyplot as plt
import sys
cam = cv2.VideoCapture(0)

while(cam.isOpened()):
    ret, frame = cam.read()     #Keep on capturing the frames continuously
    while (ret==True):
        #img = cv2.imread('/home/shrikrishna/Detection&Tracking/OpenCV-Tutorial',6)
        cv2.imwrite('At time'+ str(time.clock()) + '.jpg', frame)
        img2 = cv2.imread('At time'+ str(time.clock()) + '.jpg',6)
        t = str(time.clock())
        cv2.imshow('Orignal',frame)
        k = cv2.waitKey(0) & 0xffff
        if(k==27):              
            #img = cv2.imread('At time'+ str(time.clock()) + '.jpg',6)
            break
        if(k==ord('q')):
            sys.exit(0)
    break

#cv2.imwrite('At time'+ t + '.jpg', frame)
img = cv2.imread('At time'+ t + '.jpg',6)   

ret,thresh1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
ret,thresh2 = cv2.threshold(img,127,255,cv2.THRESH_BINARY_INV)
ret,thresh3 = cv2.threshold(img,127,255,cv2.THRESH_TRUNC)
ret,thresh4 = cv2.threshold(img,127,255,cv2.THRESH_TOZERO)
ret,thresh5 = cv2.threshold(img,127,255,cv2.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()

cv2.waitKey(0)

cv2.destroyAllWindows()

【问题讨论】:

    标签: python-3.x opencv


    【解决方案1】:

    在以下行中,您将图像读取为彩色图像(基于第二个参数 -- 标志)。

    img = cv2.imread('At time'+ t + '.jpg',6)
    

    这意味着img 包含 3 个通道,在 Python 中由 3 维数组表示。

    您立即将此图像用作阈值处理的来源:

    ret,thresh1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
    

    根据documentationthreshold()的第一个参数是:

    • src – 输入数组(单通道、8 位或 32 位浮点)。

    这意味着您需要一个单通道图像,例如一张灰度图:

    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    ret,thresh1 = cv2.threshold(img_gray,127,255,cv2.THRESH_BINARY)
    # ...
    

    另一种选择是首先将图像读取为灰度:

    img_gray = cv2.imread('At time'+ t + '.jpg',0)
    # ...
    

    【讨论】:

      猜你喜欢
      • 2020-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-29
      • 1970-01-01
      • 1970-01-01
      • 2017-12-24
      • 2017-10-08
      相关资源
      最近更新 更多