opencv-python 摄像头实时识别颜色,并输出位置

# coding:UTF-8
# v1--读取与显示图像
import numpy as np
import cv2

cap = cv2.VideoCapture(0) #设备号为0
cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M','J','P','G'))
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)

while(True):
    if cap.isOpened() == False:
        print('can not open camera')
        break
    ret, frame = cap.read() #读取图像
    if ret == False: #图像读取失败则直接进入下一次循环
        continue

    cv2.namedWindow("frame")
    cv2.imwrite('findflag.jpg',frame)  
    cv2.imshow('frame', frame)
    img_bgr = cv2.imread('./findflag.jpg')                  # 读取彩色图像
    img_hsv = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2HSV)      # 转化为 HSV 格式
    thresh1 = np.array([0, 120, 120])                       # 目标红旗的低阈值
    thresh2 = np.array([10, 255, 255])                      # 目标红旗的高阈值
    img_flag = cv2.inRange(img_hsv, thresh1, thresh2)       # 获取红旗部分
    
    ## 形态学滤波
    img_morph = img_flag.copy()                             # 复制图像
    cv2.erode(img_morph, (3,3), img_morph, iterations= 3)   # 腐蚀运算
    cv2.dilate(img_morph, (3,3), img_morph, iterations= 3)  # 膨胀运算


    ## 获取图像特征
    cnts, _ = cv2.findContours(img_morph, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # 获取图像轮廓
    cnts_sort = sorted(cnts, key= cv2.contourArea, reverse= True) # 将轮廓包含面积从大到小排列
    if cnts_sort:
        box = cv2.minAreaRect(cnts_sort[0])                     # 选取包含最大面积的轮廓,并得出最小外接矩形
        points = np.int0(cv2.boxPoints(box))                    # 获得该矩形的四个定点
    
        cen_v = (points[0,0] + points[2,0]) / 2                 # 得出横向中心
        cen_h = (points[0,1] + points[2,1]) / 2                 # 得出纵向中心
        rows, cols = img_bgr.shape[:2]
        print ('彩色图像大小: (' + str(cols) + ', ' + str(rows) + ')')
        print ('目标中心位置: (' + str(cen_h) + ', ' + str(cen_v) + ')')
        if cen_v<300 and cen_v>0 :
            print ('left')
        else:
            print ('right')
        

        cv2.drawContours(img_bgr, [points], -1, (255,0,0), 2)         # 在原图上绘制轮廓

    ## 显示图像  
    cv2.imshow('框选', img_bgr)                                    
    cv2.imshow('red', img_flag)
    cv2.imshow('滤波', img_morph)
    mykey = cv2.waitKey(1)
	#按q退出循环,0xFF是为了排除一些功能键对q的ASCII码的影响
    if mykey & 0xFF == ord('q'):
        break

cap.release()
cv2.waitKey(0)
cv2.destroyAllWindows()

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值