求助基于python串口通信程序报错,显示serial.serialutil.PortNotOpenError: Attempting to use a port that is,怎么修改

Mr.W421 Mr.W421 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

用pycharm写的,手势识别的手势数字通过串口发送到单片机上,这里用的虚拟串口来测试,看能不能接收到数据,之前运行成功了,结果后面又开始报错,麻烦大神帮我看看!!!

import cv2
import mediapipe as mp
import time
import serial


class handDetector():
    def __init__(self, mode=False, maxHands=2, model_complexity=1, detectionCon=0.8, trackCon=0.8):
        self.mode = mode
        self.maxHands = maxHands
        self.detectionCon = detectionCon
        self.trackCon = trackCon
        self.model_complexity = model_complexity

        #初始化手部识别模型
        self.mpHands = mp.solutions.hands
        self.hands = self.mpHands.Hands(self.mode, self.maxHands, self.model_complexity, self.detectionCon, self.trackCon)
        self.mpDraw = mp.solutions.drawing_utils
        self.tipIds = [4, 8, 12, 16, 20]

    def findHands(self, img, draw=True):
        imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        self.results = self.hands.process(imgRGB)

        print(self.results.multi_handedness)  # 获取检测结果中的左右手标签并打印

        if self.results.multi_hand_landmarks:
            for handLms in self.results.multi_hand_landmarks:
                if draw:
                    self.mpDraw.draw_landmarks(img, handLms, self.mpHands.HAND_CONNECTIONS)
        return img

    def findPosition(self, img, draw=True):
        self.lmList = []
        if self.results.multi_hand_landmarks:
            for handLms in self.results.multi_hand_landmarks:
                for id, lm in enumerate(handLms.landmark):
                    h, w, c = img.shape
                    cx, cy = int(lm.x * w), int(lm.y * h)
                    # print(id, cx, cy)
                    self.lmList.append([id, cx, cy])
                    if draw:
                        cv2.circle(img, (cx, cy), 12, (255, 0, 255), cv2.FILLED)
        return self.lmList

    def fingersUp(self):
        fingers = []
        # 大拇指
        if self.lmList[self.tipIds[0]][1] > self.lmList[self.tipIds[0] - 1][1]:
            fingers.append(1)
        else:
            fingers.append(0)

        # 其余手指
        for id in range(1, 5):
            if self.lmList[self.tipIds[id]][2] < self.lmList[self.tipIds[id] - 2][2]:
                fingers.append(1)
            else:
                fingers.append(0)

        # totalFingers = fingers.count(1)
        return fingers


wCam, hCam = 640, 480
#############################
cap = cv2.VideoCapture(0)  # 若使用笔记本自带摄像头则编号为0  若使用外接摄像头 则更改为1或其他编号
cap.set(3, wCam)
cap.set(4, hCam)
pTime = 0
detector = handDetector()
#定义一个手势数字字典
values = {
            0: "0",
            1: "1",
            2: "2",
            3: "3",
            4: "4",
            5: "5",
}
#串口通信
#串口通信
ser = serial.Serial()
ser.baudrate = 115200
ser.port = "COM2"
ser.open()     #打开串口



#手势识别
while True:
    success, img = cap.read()
    img = detector.findHands(img)
    lmList = detector.findPosition(img, draw=False)
    pointList = [4, 8, 12, 16, 20]
    if len(lmList) != 0:
        countList = []
        # 大拇指
        if lmList[4][1] > lmList[3][1]:
            countList.append(1)
        else:
            countList.append(0)
        # 余下四个手指
        for i in range(1, 5):
            if lmList[pointList[i]][2] < lmList[pointList[i] - 2][2]:
                countList.append(1)
            else:
                countList.append(0)
        print(countList)
        count = countList.count(1)  # 对列表中含有的1计数(计数值为手势数字)
        print(count)
        HandImage = cv2.imread(f'FingerImg/{count}.jpg')
        HandImage = cv2.resize(HandImage, (150, 200))
        h, w, c = HandImage.shape
        img[0:h, 0:w] = HandImage
        cv2.putText(img, str(count), (15, 400), cv2.FONT_HERSHEY_PLAIN, 15, (255, 0, 255), 10)
        data = values.get(count)
        print(data)
        ser.write(str(data).encode("gbk"))
        print('python send:\\n', data)


    cTime = time.time()
    fps = 1 / (cTime - pTime)
    pTime = cTime
    cv2.putText(img, f'fps: {int(fps)}', (600, 40), cv2.FONT_HERSHEY_PLAIN, 2, (255, 0, 0), 2)

    cv2.imshow("Image", img)
    cv2.waitKey(1)
    ser.close()

这里是错误

Traceback (most recent call last):
  File "D:/基于机器视觉的手势控制项目开发/基于机器视觉的手势控制项目开发/xiangmu/HandTrackingModule.py", line 119, in <module>
    ser.write(str(data).encode("gbk"))
  File "F:\anaconda\lib\site-packages\serial\serialwin32.py", line 306, in write
    raise PortNotOpenError()
serial.serialutil.PortNotOpenError: Attempting to use a port that is not open
5
 

...全文

相关推荐

对python3 Serial 串口助手的接收读取数据方法详解

今天小编就为大家分享一篇对python3 Serial 串口助手的接收读取数据方法详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

weixin_38684509

Python Serial串口基本操作(收发数据)

1、需要模块以及测试工具 模块名:pyserial 使用命令下载:python -m pip install pyserial 串口调试工具:sscom5.13.1.exe 2、导入模块 import serial 3、打开串口 直接通过new一个Serial()的实例即可打开 返回实例 # encoding=utf-8 import serial if __name__ == '__main__': com = serial.Serial('COM3', 115200) print com 运行结果 Serial(port=’CO

weixin_38672807

python实现串口通信的示例代码

1 硬件设备 TTL串口摄像头(VC0706) USB转TTL烧录器 2 serial安装 第一次安装的是serial的包导包的时候发现下载错了,正确应该是pyserial。安装后直接import就可以了。 3 实现串口通信 3.1 发现端口 Windows下为COM(N, N=1、2…), Ubuntu下为‘/dev/ttyS0‘。Windows初学者,可以给您一下两种方式确定端口号。 方法一:输入在终端(cmd)中输入 python -m serial.tools.list_ports 输出结果: COM5 1 ports found 方法二:搜索电脑上的设备管理器,打开以后然

weixin_38621638

Python实现串口通信(pyserial)过程解析

主要介绍了Python实现串口通信(pyserial)过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

weixin_38590309

Python使用pyserial进行串口通信的实例

今天小编就为大家分享一篇Python使用pyserial进行串口通信的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

weixin_38617001
评论 2
收藏 已收藏
分享
返回顶部
Mr.W421
脚本语言 37,738 成员 34,208 内容