如何同时 运行 OpenCV 和 Arduino PySerial

How to run OpenCV and Arduino PySerial simultaneously

我正在尝试使用 Arduino Uno 通过网络摄像头拍摄快照照片。我正在使用 python OpenCV 与摄像头连接以捕获视频。我还在 Arduino 接口上使用 pyserial,这样当按下按钮时,Arduino 和 python 将交互并且相机将拍照。我遇到的问题是,当我 运行 为 Arduino 建立串行连接时,网络摄像头 window 不加载视频 e.i。 (未响应)。当我注释掉与串行接口有关的代码行时,相机 window 帧加载,我可以观看视频。我在想,因为这两个设备都通过 USB 连接到我的电脑,PySerial 正在接管串行接口,不允许摄像头视频将其数据加载到接口上供我查看。我的问题是有没有办法将两者连接在一起,以便当 Arduino 接收到数字输入时,它会向 python 发送“命令”以使网络摄像头拍照?任何建议将不胜感激。

平台:

Windows 10 Python3.8

Python代码:

 import cv2
 import serial

 cam = cv2.VideoCapture(0)
 ser = serial.Serial('COM7', 9600)
 cv2.namedWindow("Object")
 img_counter = 0

 while True:
    ret, frame = cam.read()
    snap = ser.read()
    ser.reset_input_buffer()
    
    if not ret:
        print("failed to grab frame")
        break
        cv2.imshow("Object", frame)

    k = cv2.waitKey(1)
    if k%256 == 27:
        # ESC pressed
        print("Program closing...")
        break
    
    elif str(snap) == '1':
        # Button pressed
        img_name = "opencv_frame_{}.png".format(img_counter)
        cv2.imwrite(img_name, frame)
        print("{} written!".format(img_name))
        img_counter += 1

cam.release()

cv2.destroyAllWindows()             

P.S。如果这个问题看起来很基本,请原谅,我是这个工作范围的新手。我正在创建这个学校项目来连接神经网络和 PLC。我还有一个 Rasberry Pi,我可以用它来 运行 神经网络,但这对我来说是另一个有学习曲线的领域,哈哈。

输入串行连接超时。

ser=serial.Serial(port='comX',baudrate=9600,timeout=.1) #timeout - float type

我认为没有用 read(),而是 readline()。您可以转换此数据(如果是整数)。

#write this in while 
try:
    dat=ser.readline()
    try:
        datInt=int(dat)
    except:
        print('Convert fail')#often readed b'', and may not converted
except:
    print('Serial connecting fail')

这个datInt值就是写入的整数。 如果不是intiger,你可以使用string方法,并用更多命令转换。

如果您将列出或阅读更多数据,请在此留言。

祝你好运!

(对不起我的英语不完美)