程序运行流程为:
- 运行PC端代码,电脑等待串口接收图片数据
- 波特率最高921600
- 运行openmv代码,openmv使用snapshot方法采集一张图片,进行压缩并发送
- 电脑收到图片数据,解码为一张图片,并保存为jpg格式,发送#表示完成
- openmv接收到#后停止发送图像
OPENMV端
import sensor, image, time, ustruct, pyb
def init_camera():
sensor.reset()
sensor.set_pixformat(sensor.JPEG) # 直接设置为JPEG格式,减少压缩步骤
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(time=2000)
def send_image_via_uart(uart, img):
# img_bytes = img.getbytes()
length = len(img)
uart.write(ustruct.pack("<I", length)) # 发送长度
uart.write(img) # 发送图片数据
def main():
uart = pyb.UART(3, baudrate=921600, timeout=1000)
init_camera()
while True:
img = sensor.snapshot()
send_image_via_uart(uart, img)
print("图片已发送")
time.sleep(1) # 添加延时,避免过快发送
if __name__ == "__main__":
main()
PC端
import serial, struct, tkinter as tk, PIL.Image, PIL.ImageTk, io, threading
class ImageReceiver(threading.Thread):
def __init__(self, serial_port):
threading.Thread.__init__(self)
self.ser = serial.Serial(serial_port, 921600, timeout=1)
self.root = tk.Tk()
self.root.title("接收并显示OpenMV图片")
self.image_label = tk.Label(self.root)
self.image_label.pack()
self.running = True
def run(self):
while self.running:
self.receive_image()
def receive_image(self):
try:
# 读取图片长度
length_bytes = self.ser.read(4)
if len(length_bytes) != 4:
print("长度信息接收错误")
return
img_length = struct.unpack("<I", length_bytes)[0]
# 读取图片数据
img_bytes = bytearray()
while len(img_bytes) < img_length:
chunk = self.ser.read(min(img_length - len(img_bytes), 1024))
if not chunk:
break
img_bytes.extend(chunk)
if len(img_bytes) != img_length:
print("图片数据接收不完整")
return
# 显示图片
self.display_image(img_bytes)
except Exception as e:
print(f"接收图片时发生错误: {e}")
def display_image(self, img_bytes):
try:
img = PIL.Image.open(io.BytesIO(img_bytes))
tk_img = PIL.ImageTk.PhotoImage(img)
self.image_label.config(image=tk_img)
self.image_label.image = tk_img # 保持引用
except Exception as e:
print(f"显示图片时发生错误: {e}")
def stop(self):
self.running = False
self.ser.close()
self.root.quit()
if __name__ == "__main__":
receiver = ImageReceiver('COM23') # 根据你的串口名修改
receiver.start()
receiver.root.mainloop()
receiver.stop()
标签:img,self,电脑,照片,串口,sensor,image,def,openmv
From: https://blog.csdn.net/2301_80317247/article/details/143844067