简体   繁体   English

使用Opencv python2.7检测矩形

[英]using Opencv python2.7 to detect a rectangle

I have written a python code using opencv to detect a rectangle (displaying height, and width) also determine the distance from camera to the object but when i run the code i get this error(can be found below) i don't know what am doing wrong please i would appreciate it if anyone could help me out i have tried every possible solution that i could find but still can't rid of the error. 我已经使用opencv编写了python代码来检测矩形(显示高度和宽度),并且还确定了相机到对象的距离,但是当我运行代码时,出现此错误(可以在下面找到),我不知道是什么我做错了,如果有人可以帮助我,我将不胜感激,我尝试了所有可能找到的解决方案,但仍然无法消除错误。

ERROR 错误

yuv_red = cv2.cvtColor(frame, cv2.COLOR_BGR2YUV) error: C:\\builds\\master_PackSlaveAddon-win32-vc12-static\\opencv\\modules\\imgproc\\src\\color.cpp:8059: error: (-215) scn == 3 || yuv_red = cv2.cvtColor(frame,cv2.COLOR_BGR2YUV)错误:C:\\ builds \\ master_PackSlaveAddon-win32-vc12-static \\ opencv \\ modules \\ imgproc \\ src \\ color.cpp:8059:错误:(-215)scn == 3 || scn == 4 in function cv::cvtColor scn == 4在函数cv :: cvtColor中

  import sys
sys.path.append('C:\Python27\Lib\site-packages')
import cv2
import numpy as np
import argparse
import math

############################# Capturing Video Through Camera ########################
cap = cv2.VideoCapture(0)

############# Distance to Camera initial value set to zero ##########################
Distance_to_Camera=0

while(True):

#################################  Capture frame-by-frame ###########################
    ret, frame = cap.read()

############################ Converting frame(img i.e BGR to YUV) ###################
    yuv_red = cv2.cvtColor(frame, cv2.COLOR_BGR2YUV)

    red_color = np.uint8([[[0,0,255]]])
    yuv_color = cv2.cvtColor(red_color,cv2.COLOR_BGR2YUV)
    print yuv_color

############################### Processing of Image  ##############################

#####################   Defining the Range of Red Colour  ###########################
    red_lower = np.array([136,87,111],np.uint8)
    red_upper = np.array([180,255,255],np.uint8)

##################### Finding the Range of Red Colour in the image ###################
    mask = cv2.inRange(yuv_red, red_lower,red_upper)

####################### Morphological Transformation, Dilation #######################   

    res = cv2.bitwise_and(frame, frame, mask = mask)

##################################################################################### 
    gray = cv2.cvtColor(res,cv2.COLOR_BGR2GRAY)      #Converting the BGR res to Gray
    blurred = cv2.GaussianBlur(gray, (5,5), 5)       #Blur Image to remove noise  
    blur = cv2.bilateralFilter(blurred, 5,50,50)     #Smooth the image
    median = cv2.medianBlur(blur,5)                  #Reduce noise from image 
    thresh = cv2.threshold(median, 3, 255, cv2.THRESH_BINARY)[1] #To achieve a better output of white and black

    frame2, contour, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

#####################  Splitting and Merging Image channels ###########################
    b,g,r = cv2.split(res)
    ttl = res.size/3
    Ra = float(np.sum(r))/ ttl
    print Ra

    if Ra > 1:
        c = contours[0]
        M = cv2.moments(c)
        x = int(M['m10']/M['m00'])
        y = int(M['m01']/M['m00'])

        x,y,w,h = cv2.boundingRect(c)
        epsilon = 0.01*cv2.arcLength(c, True)
        approx = cv2.approxPolyDP(c, epsilon, True)
        perimeter = cv2.approxLength(c,True)
        area = cv2.contourArea(c)
        ah = h/40
        aw = w/40



        Distance_to_Camera = round(math.sqrt(315/area),4)
        print Distance_to_Camera

        approx = cv2.approxPolyDP(c, epsilon, True)
        print   len(approx)
        shape = len(approx)

        if shape == 4:
            print " 4 Sides"
            rect = cv2.minAreaRect(c)
            box = cv2.boxPoints(rect)
            box = np.int0(box)
            cv2.drawContours(frame,ArithmeticError[box],0,(0,0,255),0)
            print box

        if ah == aw:
################################  Displaying Text on the Image ################################
            print "Unknown"
            cv2.putTextputText(frame,"Unknown",(x+150,y+150),cv2.FONT_HERSHEY_SIMPLEX,2,(255,255,255),4)
        else:

 ################################  Displaying Text on the Image ################################           

            print "Rectangle"
            cv2.putTextputText(frame,"Rectangle",(x+150,y+150),cv2.FONT_HERSHEY_SIMPLEX,2,(255,255,255),4)

            output = ("Distance="+str((round((distance+0.0004)*1000))) + "cm" + "X=" + str(aw)+"cm" +"Y="+str(ah)+"cm"+"Perimeter=" +str(round(perimeter/40))+"cm"+"Area="+str(round((area/1.64)/1000))+"cm^2")
            cv2.imshow('gray',frame)

    else:
        cv2.imshow('gray',frame)

##########################################  Output ##########################################
        cv2.imshow('gray',frame)
        cv2.imshow('grayscaled',thresh)

    if cv2.waitKey(20) & 0xFF == 27:
        break

##if k == 27:         # wait for ESC key to exit
##    cv2.destroyAllWindows()

# When everything done, release the capture
    cv2.destroyAllWindows()
    cap.release()



















  [1]: https://i.stack.imgur.com/qB2rx.png

In the line implementing a bilateral filter you have an erroneous parenthesis: 在实现双边过滤器的行中,您有一个错误的括号:

blur = cv2.bilateralFilter(blurred, (5,50,50)

Check out the docs for cv2.bilateralFilter() to see the proper use. 查看文档,了解cv2.bilateralFilter()的用法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM