用于视频中文本检测的Python代码不起作用?

时间:2016-06-04 13:50:50

标签: python opencv opencv3.0

我在视频中使用此代码进行文本检测,并且每次尝试运行时都会出现此错误。

这是我的代码:

import cv2
import numpy as np
#from pytesser import *

def text_detection():
   cap=cv2.VideoCapture(0)
    while True:
        ret,img=cap.read()
        gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
        ret1,mask= cv2.threshold(gray,180,255,cv2.THRESH_BINARY)
        image_final=cv2.bitwise_and(gray,gray,mask=mask)
        ret2,new_img= cv2.threshold(image_final,180,255,cv2.THRESH_BINARY)
        kernel=cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3))
        dilated=cv2.dilate(new_img,kernel,iterations=9)
        idk,contours,hierarchy=cv2.findContours(dilated,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
        for contour in contours:
            [x,y,w,h]=cv2. boundingRect(contour)

            if w<35 and h<35:
                continue

         cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,255),2)

         cv2.imshow('text_detect',img)
         k=cv2.waitKey(1)& 0xff
         if k==ord('q'):
            break
         cap.release()
         cv2.destroyAllWindows()



text_detection()

错误:

  

灰色= cv2.cvtColor(IMG,cv2.COLOR_BGR2GRAY)        cv2.error:D:\ Build \ OpenCV \ opencv-3.1.0 \ modules \ imgproc \ src \ color.cpp:7456:   错误:( - 1515)scn == 3 || scn == 4 in function cv :: ipp_cvtColor

请帮帮我。

2 个答案:

答案 0 :(得分:0)

看起来你忘了打开()凸轮。

import cv2

cam = cv2.VideoCapture(0)
cam.open(0)
results = [ cam.read()[0] for i in range(100) ]
print results

此代码段应设置,打开并验证捕获是否适用于100次捕获。

答案 1 :(得分:0)

在将其转换为灰度之前似乎没有捕获到任何帧。 您应该添加检查以确认是否已捕获帧,然后再进一步处理

import time

def text_detection():
   cap=cv2.VideoCapture(0)
    while True:
        ret,img=cap.read()

        """ adding 0.5 sec delay and verifying if the frame is captured or not.
            It will print the message if the frame is not captured. """

        time.sleep(0.5)
        if not ret:
           print('No frame is captured')
           break

        gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
        ret1,mask= cv2.threshold(gray,180,255,cv2.THRESH_BINARY)

""" 
perform your normal processing

"""