【问题标题】:How do I fix openCV cvtColor error in my project?如何修复项目中的 openCV cvtColor 错误?
【发布时间】:2019-07-29 14:28:47
【问题描述】:

我正在构建手写识别项目,但我在尝试从 BGR2HSV 更改图像时收到此错误 cvtColor

cap = cv2.VideoCapture(0)
Lower_blue = np.array([110, 50, 50])
Upper_blue = np.array([130, 255, 255])
pred_class = 0
pts = deque(maxlen = 512)
blackboard = np.zeros((480, 640, 3), dtype = np.uint8)
digit = np.zeros((200, 200, 3), dtype = np.uint8)
while(cap.isOpened()):
    ret, img = cap.read()
    img = cv2.flip(img, 1)
    imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    mask = cv2.inRange(imgHSV, Lower_blue, Upper_blue)
    blur = cv2.medianBlur(mask, 15)
    blur = cv2.GaussianBlur(blur, (5, 5), 0)
    thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY +   cv2.THRESH_OTSU)[1]
    cnts = cv2.findContours(thresh.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[1]
    center = None
    if len(cnts) >= 1:
        contour = max(cnts, key = cv2.contourArea)
        if cv2.contourArea(contour) > 250:
            ((x, y), radius) = cv2.minEnclosingCircle(contour)
            cv2.circle(img, (int(x), int(y)), int(radius), (0, 255, 255), 2)
            cv2.circle(img, center, 5, (0, 255, 255), -1)
            M = cv2.moments(contour)
            center = (int(M['m10'] / M['m00']), int(M['m01'] / M['m00']))
            pts.appendleft(center)
            for i in range (1, len(pts)):
                if pts[i - 1] is None or pts[i] is None:
                    continue
                cv2.line(blackboard, pts[i - 1], pts[i], (255, 255, 255), 10)
                cv2.line(img, pts[i - 1], pts[i], (0, 0,255), 5)
    elif len(cnts) == 0:
        if len(pts) != []:
            blackboard_gray = cv2.cvtColor(blackboard, cv2.COLOR_BGR2GRAY)
            blur1 = cv2.medianBlur(blackboard_gray, 15)
            blur1 = cv2.GaussianBlur(blur1, (5, 5), 0)
            thresh1 = cv2.threshold(blur1, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
            blackboard_cnts = cv2.findContours(thresh1.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[1]
            if len(blackboard_cnts) >= 1:
                cnt = max(blackboard_cnts, key = cv2.contourArea)
                print(cv2.contourArea(cnt))
                if cv2.contourArea(cnt) > 2000:
                    x, y, w, h = cv2.boundingRect(cnt)
                    digit = blackboard_gray[y:y + h, x:x + w]
                    #new Image = process_letter(digit)
                    pred_probab, pred_class = keras_predict(model1, digit)
                    print(pred_class, pred_probab)

            pts = deque(maxlen = 512)
            blackboard = np.zeros((480, 640, 3), dtype = uint8)
        cv2.putText(img, "Conv Network : " + str(letter_count    [pred_class]), (10, 470),
                cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
        cv2.imshow("Frame", img)
        cv2.imshow("Contours", thresh)

        k = cv2.waitkey(10)
        if k == 27:
            break

如何解决这个 OpenCV 错误问题?请帮忙!

我收到以下错误:

error: OpenCV(3.4.1) C:\Miniconda3\conda-bld\opencv-suite_1533128839831\work\modules\imgproc\src\color.cpp:11214: error: (-215) (scn == 3 || scn == 4) && (depth == 0 || depth == 5) in function cv::cvtColor

【问题讨论】:

    标签: python python-3.x opencv machine-learning


    【解决方案1】:

    我认为以下错误:error: (-215) (scn == 3 || scn == 4) && (depth == 0 || depth == 5) in function cv::cvtColor 是因为相机无法正确捕获帧。通过打印ret 值来检查这一点。如果相机能够正确捕获帧,它将返回True,否则返回False。发生上述错误是因为 None 被传递给 cv2.cvtColor 函数。您可以使用以下代码作为安全检查:

    if ret is True:
       # your code goes here
    else:
       break
    

    此外,请考虑以下几点:

    • cv2.waitKey(10),而不是cv2.waitkey(10)[大写'K']
    • cv2.findContours 函数在 OpenCV 3.x 中返回 3 值(即图像、轮廓和层次结构),但在 openCV 4.x 中返回 2 值(即轮廓、层次结构)
    • len(pts) != [] 没有意义。在这里,您试图将一个数字与一个空列表进行比较。将其更改为len(pts) != 0
    • cv2.putText 函数中的letter_count 是什么。请重新检查。
    • len(cnts)==0len(pts) != 0 的情况下,您可以使用旧的pts,而不是重新初始化双端队列(pts = deque(maxlen = 512)),只需使用pts.clear() 将其清除即可。只是一个想法!
    • 另外,在末尾添加以下代码:

      cap.release() 
      cv2.destroyAllWindows() 
      

    试试下面的修改代码(使用openCV v4.0.0测试):

    import cv2
    import numpy as np
    from collections import deque
    
    cap = cv2.VideoCapture(0)
    Lower_blue = np.array([110, 50, 50])
    Upper_blue = np.array([130, 255, 255])
    pred_class = 0
    pts = deque(maxlen = 512)
    blackboard = np.zeros((480, 640, 3), dtype = np.uint8)
    digit = np.zeros((200, 200, 3), dtype = np.uint8)
    
    while(cap.isOpened()):
        ret, img = cap.read()
        img = cv2.flip(img, 1)
        imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
        mask = cv2.inRange(imgHSV, Lower_blue, Upper_blue)
        blur = cv2.medianBlur(mask, 15)
        blur = cv2.GaussianBlur(blur, (5, 5), 0)
        thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY +   cv2.THRESH_OTSU)[1]
        cnts = cv2.findContours(thresh.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[0]
        center = None
        if len(cnts) >= 1:
            contour = max(cnts, key = cv2.contourArea)
            if cv2.contourArea(contour) > 250:
                ((x, y), radius) = cv2.minEnclosingCircle(contour)
                cv2.circle(img, (int(x), int(y)), int(radius), (0, 255, 255), 2)
                cv2.circle(img, center, 5, (0, 255, 255), -1)
                M = cv2.moments(contour)
                center = (int(M['m10'] / M['m00']), int(M['m01'] / M['m00']))
                pts.appendleft(center)
                # print(pts)
                for i in range (1, len(pts)):
                    if pts[i - 1] is None or pts[i] is None:
                        print("Continue")
                        continue
                    cv2.line(blackboard, pts[i - 1], pts[i], (255, 255, 255), 10)
                    cv2.line(img, pts[i - 1], pts[i], (0, 0,255), 5)
                cv2.imshow("Frame", img)
                cv2.imshow("Contours", thresh)
    
                # press q to stop
                if cv2.waitKey(1) & 0xFF == ord('q'):
                    break
    
        else:
            if len(pts) != 0:
                blackboard_gray = cv2.cvtColor(blackboard, cv2.COLOR_BGR2GRAY)
                blur1 = cv2.medianBlur(blackboard_gray, 15)
                blur1 = cv2.GaussianBlur(blur1, (5, 5), 0)
                thresh1 = cv2.threshold(blur1, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
                print('Hello')
                blackboard_cnts = cv2.findContours(thresh1.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[0]
                if len(blackboard_cnts) >= 1:
                    cnt = max(blackboard_cnts, key = cv2.contourArea)
                    print(cv2.contourArea(cnt))
                    if cv2.contourArea(cnt) > 2000:
                        x, y, w, h = cv2.boundingRect(cnt)
                        digit = blackboard_gray[y:y + h, x:x + w]
                        #new Image = process_letter(digit)
                        #pred_probab, pred_class = keras_predict(model1, digit)
                        print(digit.shape)
    
                #pts = deque(maxlen = 512)
                pts.clear()
                blackboard = np.zeros((480, 640, 3), dtype = np.uint8)
                #cv2.putText(img, "Conv Network : " + str(letter_count[pred_class]), (10, 470), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
                cv2.putText(img, "Conv Network :", (10, 470), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
    
                cv2.imshow("Frame", img)
                cv2.imshow("Contours", thresh)
    
                if cv2.waitKey(1) & 0xFF == ord('q'):
                    break
    
    cap.release()
    cv2.destroyAllWindows()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-08
      • 2017-03-02
      • 1970-01-01
      • 2020-09-27
      • 2021-11-18
      • 1970-01-01
      • 2019-10-07
      • 2021-05-21
      相关资源
      最近更新 更多