opencv形状检测中遇到的报错及解决

首先,给出源码:

#一
import cv2
import numpy as np
import serial
#import imutils   use pip to install but find nothing?  
image_path='/home/pi/photo/image.jpg'


class check:
    #get original image
    def get_original(image_path):
        # 初始化摄像头
        cap = cv2.VideoCapture(0)
        
        # 检查摄像头是否成功打开
        if not cap.isOpened():
            print("无法打开摄像头")
            return
        
        while True:
            # 捕获图像
            ret, frame = cap.read()
            height,width,channels = frame.shape
            # 检查图像是否成功捕获
            if not ret:
                print("无法捕获图像")
                break
            
            # 自动曝光和白平衡
            #frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)  # 转为RGB格式
            #balance_frame = cv2.xphoto.createSimpleWB().balanceWhite(frame)

            # 显示图像
            
            cv2.imshow("Camera", frame)
            
            # 按下 'q' 键结束拍摄
            if cv2.waitKey(1) & 0xFF == ord('q'):
                # 存储图像
                cv2.imwrite(image_path, frame)
                break
        
        # 释放摄像头
        cap.release()
        print(height)
        print(width)
        print(channels)
        # 销毁窗口
        cv2.destroyAllWindows()

        print("图像已保存至", image_path)
    #def jiaozheng(): 
        
    def pattern_recognition(src):
        # 图像预处理
        gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
        
        thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
        #this place is wrong
        # 轮廓查找
        contours = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        conPoly = []  # 多边形逼近结果,与轮廓一一对应
        contours=contours[1] #if imutils.is_cv3() else contours[0]
        #later wrods tell us to judge version is 3 or 4 ,return true to use [1]
        print('contours',contours)
        cv2.imshow("thresh", thresh)
        for contour in contours:
            area = cv2.contourArea(contour)  # 轮廓面积

            if area > 1000:
                rect = cv2.boundingRect(contour)  # 外界矩形

                ratio = rect[2] / rect[3]  # 长宽比

                peri = cv2.arcLength(contour, True)  # 周长

                approx = cv2.approxPolyDP(contour, 0.02 * peri, True)  # 多边形近似
                objSize = len(approx)  # 折线数--通过判断轮廓有几条边来识别图形

                objName = ""
                color = ()
                if objSize == 3:
                    objName = "Triangle"  # 三角形
                    color = (0, 0, 255)
                elif objSize == 4:
                    # 通过长宽比判断正方形/长方形
                    if 0.99 < ratio < 1.01:
                        objName = "Square"  # 正方形
                        color = (0, 255, 255)
                    else:
                        objName = "Rectangle"  # 长方形
                        color = (0, 255, 0)
                elif objSize == 8:
                    objName = "Circle"  # 圆形
                    color = (255, 255, 0)
                elif objSize == 10:
                    objName = "Star"  # 星形
                    color = (255, 0, 255)
                # 效果绘制
                    x,y,w,h= rect
                    pt1=(x,y)
                    pt2=(x+w,y+h)
                    cv2.rectangle(src,pt1,pt2,color,2,cv2.LINE_8)
                    cv2.putText(src, objName, rect[:2], cv2.FONT_HERSHEY_SIMPLEX, 1, color, 2)
        return objName
        #return src
    def send_data(mark):
        ser=serial.Serial("/dev/ttyAMA0",9600)
        if mark=="Rectangle":
            ser.write(b'1')
    def main():
        check.get_original(image_path)
        src = cv2.imread(image_path)
       

        if src is None:
            print("No Image!")
            return
        objName=check.pattern_recognition(src)
        check.send_data(objName)
        img_result = check.pattern_recognition(src)
        print('objName',objName)
        #cv2.imshow("img_result", img_result)
        
        cv2.waitKey(0)
        cv2.destroyAllWindows()

if __name__ == "__main__":
    check.main()

首先,第一个报错:

Assertion failed npoints >=0 &&(depth == CV_32F|| depth == CV_32S) in fuction 'contourArea'

一开始我以为是数据类型的报错,F(浮点型),S(整形),后面去上网查资料才知道是版本不兼容,我借鉴了error: (-215:Assertion failed) npoints >= 0 && (depth == CV_32F || depth == CV_32S) in function '..._BC_COM的博客-CSDN博客 直接引用了CV版本对应第二个的序列就可以了

第二个报错是:

too many values to unpack

这个其实也是版本不兼容问题,cv2.findcontours,在cv3.几版本的传回参数是一个,在cv4及以上就有两个(原本用contours,_装的),解决方法:

thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
        
        # 轮廓查找
        contours = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

总结一下,大部分奇奇怪怪的问题除去参数和格式问题大概率是版本不兼容所导致的,遇到时直接将错误复制到CSDN查询即可,一般都会有人提出解决方案。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值