判断红色和区域大小,与arduino通信-python

如题,python程序

# -*- coding:utf-8 -*-

import cv2
import numpy as np
import serial

# arduino parameter
serialPort = "COM3"  # 串口
baudRate = 9600  # 波特率
ser = serial.Serial(serialPort, baudRate, timeout=0.5)
print("参数设置:串口=%s ,波特率=%d" % (serialPort, baudRate))

demo1=b"0"
demo2=b"1"

cap = cv2.VideoCapture(0) 

# define range of red color in HSV 
lower_red1 = np.array([0,43,46]) 
upper_red1 = np.array([10,255,255])
lower_red2 = np.array([156,43,46]) 
upper_red2 = np.array([180,255,255]) 

while(1): 

    # Take each frame 
    _, frame = cap.read() 

    # Convert BGR to HSV 
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) 

    # Threshold the HSV image to get only blue colors 
    mask1 = cv2.inRange(hsv, lower_red1, upper_red1)
    mask2 = cv2.inRange(hsv, lower_red2, upper_red2)
    mask = cv2.add(mask1,mask2)
    ret, thresh = cv2.threshold(mask, 127, 255, 0)
    image,contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnt = contours[0]
    area = cv2.contourArea(cnt)
    print(area)
    if area >= 5:
        ser.write(demo2)  # ser.write在于向串口中写入数据
    else:
        ser.write(demo1)


    # Bitwise-AND mask and original image
    res = cv2.bitwise_and(frame,frame, mask= mask)

    
    
    cv2.imshow('frame',frame) 
    cv2.imshow('mask1',mask)
    cv2.imshow('res',res)
    k = cv2.waitKey(5) & 0xFF 
    if k == 27: 
     break 

cap.release()
cv2.destroyAllWindows()

arduino程序

void setup(){
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  digitalWrite(13,HIGH);
}
char var;
void loop(){
  while(Serial.available()>0)
  {
    var=Serial.read();
    if(var=='0')
    digitalWrite(13,LOW);
    if(var=='1')
    digitalWrite(13,HIGH);
  }
}

 

你可能感兴趣的:(判断红色和区域大小,与arduino通信-python)