完善资料让更多小伙伴认识你,还能领取20积分哦, 立即完善>
电子发烧友论坛|
import time, os, sys, math
import json from machine import Timer from machine import TOUCH from media.sensor import * from media.display import * from media.media import * from machine import UART from machine import FPIOA 配置引脚 fpioa = FPIOA() fpioa.set_function(11, FPIOA.UART2_TXD) fpioa.set_function(12, FPIOA.UART2_RXD) sensor_id = 2 sensor = None 初始化UART2,波特率115200,8位数据位,无校验,1位停止位 uart = UART(UART.UART2, baudrate=115200, bits=UART.EIGHTBITS, parity=UART.PARITY_NONE, stop=UART.STOPBITS_ONE) uart.write("Hello World!r") # 通过串口2输出固定字符串 “Hello World!” #阈值存储 threshold_dict = {'rect': [(54, 200)], 'red_point': [(73, 100, -4, 23, -14, 10)]} try: # 构造一个具有默认配置的摄像头对象 sensor = Sensor(id=sensor_id) # 重置摄像头sensor sensor.reset() # 无需进行镜像翻转# 设置水平镜像# sensor.set_hmirror(False)# 设置垂直翻转# sensor.set_vflip(False)# 设置通道0的输出尺寸为128x160sensor.set_framesize(width=800,height=480)# 设置通道0的输出像素格式为RGB565sensor.set_pixformat(Sensor.RGB565, chn=CAM_CHN_ID_0)# 使用IDE的帧缓冲区作为显示输出Display.init(Display.ST7701, width=800, height=480, to_ide=True)# 初始化媒体管理器MediaManager.init()# 启动传感器sensor.run()clock = time.clock()while True: clock.tick() os.exitpoint() # 捕获通道0的图像 img = sensor.snapshot(chn=CAM_CHN_ID_0) img_rect = img.to_grayscale(copy=True) img_rect = img_rect.binary(threshold_dict['rect']) # 初始化中心点变量 c_x, c_y = -1, -1 cblobs_x, cblobs_y = -1, -1 # 在图像中寻找矩形 for r in img_rect.find_rects(threshold = 120000): # 判断矩形边长是否符合要求 if r.w() > 20 and r.h() > 20: # 在屏幕上框出矩形 img.draw_rectangle(r.rect(), color = (255, 0, 0), scale = 4) # 获取矩形角点位置 corner = r.corners() # 在屏幕上圈出矩形角点 img.draw_circle(corner[0][0], corner[0][1], 5, color = (0, 0, 255), thickness = 2, fill = False) img.draw_circle(corner[1][0], corner[1][1], 5, color = (0, 0, 255), thickness = 2, fill = False) img.draw_circle(corner[2][0], corner[2][1], 5, color = (0, 0, 255), thickness = 2, fill = False) img.draw_circle(corner[3][0], corner[3][1], 5, color = (0, 0, 255), thickness = 2, fill = False) c_x = sum([corner[k][0] for k in range(4)])/4 c_y = sum([corner[k][1] for k in range(4)])/4 data = "{},{}".format(round(c_x),round(c_y)) print("{}".format([round(c_x),round(c_y)])) uart.write(data) c_x, c_y = -1, -1 img.draw_string_advanced(50, 50, 80, "fps: {}".format(clock.fps()), color=(255, 0, 0)) img.compressed_for_ide() # 显示捕获的图像 Display.show_image(img)except KeyboardInterrupt as e: print("用户停止: ", e) except BaseException as e: print(f"异常: {e}") finally: # 停止传感器运行 if isinstance(sensor, Sensor): sensor.stop() # 反初始化显示模块 Display.deinit() os.exitpoint(os.EXITPOINT_ENABLE_SLEEP) time.sleep_ms(100) # 释放媒体缓冲区 MediaManager.deinit() 上面是矩形识别,下面是调节阈值 import time import os import sys from media.sensor import * from media.display import * from media.media import * from time import ticks_ms from machine import FPIOA from machine import Pin from machine import PWM from machine import Timer from machine import TOUCH sensor = None try: sensor = Sensor(width=1920, height=1080) sensor.reset() # 鼠标悬停在函数上可以查看允许接收的参数sensor.set_framesize(width=1920, height=1080)sensor.set_pixformat(Sensor.RGB565)Display.init(Display.ST7701, to_ide=True, width=800, height=480)# 初始化媒体管理器MediaManager.init()# 启动 sensorsensor.run()fpioa = FPIOA()fpioa.help()# 设置按键fpioa.set_function(53, FPIOA.GPIO53)key = Pin(53, Pin.IN, Pin.PULL_DOWN)clock = time.clock()# 状态标识,死循环中会根据不同的flag值执行相应的逻辑# flag = 2则可以调整阈值flag = 0# 裁剪图像的ROI,格式为(x, y, w, h),推荐使用480*480的大小,此大小性能高,而且刚好可以铺满LCD屏幕cut_roi = (720, 300, 480, 480)# 向屏幕输出图像,脱机运行时可以选择注释img.compress_for_ide()来提升性能def show_img_2_screen(): global img if(img.height()>480 or img.width() > 800): scale = max(img.height() // 480, img.width() // 800) + 1 img.midpoint_pool(scale, scale) img.compress_for_ide() Display.show_image(img, x=(800-img.width())//2, y=(480-img.height())//2)# 触摸计数器,达到一定的数值后开启阈值编辑模式,防止误触touch_counter = 0# 触摸屏初始化tp = TOUCH(0)# 存储阈值threshold_dict = {'rect': [(59, 246)], 'red_point':[(47, 80, 9, 91, -55, 63), (16, 37, 23, 74, -48, 52)]}while True: clock.tick() os.exitpoint() # 如果flag = 2,则启动阈值调整功能 if flag == 2: # 清空当前的阈值 #for key_ in threshold_dict.keys(): #threshold_dict[key_] = [] button_color = (150, 150, 150) text_color = (0, 0, 0) # 创建一个画布,用来绘制按钮 img = image.Image(800, 480, image.RGB565) img.draw_rectangle(0, 0, 800, 480, color=(255, 255, 255), thickness=2, fill=True) # 按钮--返回,编辑完成后返回 img.draw_rectangle(0, 0, 160, 40, color=button_color, thickness=2, fill=True) img.draw_string_advanced(0+50, 0, 30, "返回", color=text_color) # 按钮--切换,切换编辑的阈值对象 img.draw_rectangle(800-160, 0, 160, 40, color=button_color, thickness=2, fill=True) img.draw_string_advanced(800-160+50, 0, 30, "切换", color=text_color) # 按钮--归位,滑块归位 img.draw_rectangle(0, 480-40, 160, 40, color=button_color, thickness=2, fill=True) img.draw_string_advanced(0+50, 480-40, 30, "归位", color=text_color) # 按钮--保存,将当前阈值添加到阈值列表中 img.draw_rectangle(800-160, 480-40, 160, 40, color=button_color, thickness=2, fill=True) img.draw_string_advanced(800-160+50, 480-40, 30, "保存", color=text_color) button_labels = [ "Lmin-", "Lmax-", "Amin-", "Amax-", "Bmin-", "Bmax-", "Lmin+", "Lmax+", "Amin+", "Amax+", "Bmin+", "Bmax+" ] # 左边6个按钮(0-5) for i, label in enumerate(button_labels[:6]): y_pos = 60 + i * 60 img.draw_rectangle(0, y_pos, 160, 40, color=button_color, thickness=2, fill=True) img.draw_string_advanced(0 + 40, y_pos + 10, 20, label, color=text_color) # 右边6个按钮(6-11) for i, label in enumerate(button_labels[6:]): y_pos = 60 + i * 60 img.draw_rectangle(800-160, y_pos, 160, 40, color=button_color, thickness=2, fill=True) img.draw_string_advanced(800-160 + 40, y_pos + 10, 20, label, color=text_color) # 定义一个函数,判断按下的按钮是哪一个,滑块按钮左边依次为0~5,右边依次为6~11 def witch_key(x, y): if x < 160: if y < 40: return "return" if y > 480 - 40: return "reset" if not y > 60: return None if (y - 60) % 60 < 40: return str((y - 60) // 60) elif x > 800-160: if y < 40: return "change" if y > 480 - 40: return "save" if not y > 60: return None if (y - 60) % 60 < 40: return str((y - 60) // 60 + 6) return None # 可以调多个阈值 threshold_mode_lst = list(threshold_dict.keys()) threshold_mode = 'rect' if threshold_dict[threshold_mode]: # 如果该模式有保存的阈值 if threshold_mode == 'rect': threshold_current = list(threshold_dict[threshold_mode][-1]) + [0, 255, 0, 255] else: threshold_current = [i + 127 for i in threshold_dict[threshold_mode][-1]] else: # 如果没有保存过,使用默认值 threshold_current = [0, 255, 0, 255, 0, 255] while True: img_ = sensor.snapshot(chn=CAM_CHN_ID_0) img_ = img_.copy(roi=cut_roi) print(threshold_mode) if threshold_mode == 'rect': img_ = img_.to_grayscale() img_ = img_.binary([threshold_current[:2]]) img_ = img_.to_rgb565() elif threshold_mode == 'red_point': img_ = img_.binary([[i - 128 for i in threshold_current]]) img_ = img_.to_rgb565() img.draw_image(img_, (800-img_.width()) // 2, (480-img_.height()) // 2) if threshold_mode == 'rect': threshold_text = f"阈值: {threshold_current[0]}-{threshold_current[1]}" else: threshold_text = f"阈值: L({threshold_current[0]}-{threshold_current[1]}) A({threshold_current[2]}-{threshold_current[3]}) B({threshold_current[4]}-{threshold_current[5]})" img.draw_string_advanced(170, 70, 30, threshold_text, color=(0, 0, 255)) # 显示当前调整的模式 img.draw_string_advanced(200, 20, 30, f"当前模式: {threshold_mode}", color=(0, 0, 255)) points = tp.read() if len(points) > 0: # 判断按下了哪个键 button_ = witch_key(points[0].x, points[0].y) if button_: # 如果是返回键 if button_ == "return": flag = 0 time.sleep_ms(2000) break # 如果是切换键 elif button_ == "change": threshold_mode = threshold_mode_lst[(threshold_mode_lst.index(threshold_mode) + 1) % len(threshold_mode_lst)] img.draw_rectangle(200, 200, 300, 40, color=button_color, thickness=2, fill=True) img.draw_string_advanced(200, 200, 30, "调整:{}".format(threshold_mode), color=text_color) show_img_2_screen() time.sleep_ms(3000) # 如果是归位键 elif button_ == "reset": threshold_current = [0, 255, 0, 255, 0, 255] img.draw_rectangle(200, 200, 300, 40, color=button_color, thickness=2, fill=True) img.draw_string_advanced(200, 200, 30, "滑块归零", color=text_color) show_img_2_screen() time.sleep_ms(3000) # 如果是保存键 elif button_ == "save": if threshold_mode == 'red_point': threshold_dict[threshold_mode].append([i - 127 for i in threshold_current]) elif threshold_mode == 'rect': threshold_dict[threshold_mode].append(threshold_current[:2]) img.draw_rectangle(200, 200, 300, 40, color=button_color, thickness=2, fill=True) img.draw_string_advanced(200, 200, 30, "保存成功", color=text_color) show_img_2_screen() time.sleep_ms(3000) else: print("OK") if int(button_) >= 6: threshold_current[int(button_)-6] = min(255, threshold_current[int(button_)-6]+1 ) elif int(button_) < 6: threshold_current[int(button_)] = max(0, threshold_current[int(button_)]-1) print(threshold_current) show_img_2_screen() else: img = sensor.snapshot(chn=CAM_CHN_ID_0) img = img.copy(roi=cut_roi) img.draw_string_advanced(50, 50, 80, "fps: {}".format(clock.fps()), color=(255, 0, 0)) show_img_2_screen() # 实现一个长按屏幕进入阈值编辑模式的效果 points = tp.read() if len(points) > 0: touch_counter += 1 if touch_counter > 20: flag = 2 print(points[0].x) else: touch_counter -= 2 touch_counter = max(0, touch_counter)except KeyboardInterrupt as e: print("用户停止: ", e) except BaseException as e: print(f"异常: {e}") finally: if isinstance(sensor, Sensor): sensor.stop() Display.deinit() os.exitpoint(os.EXITPOINT_ENABLE_SLEEP) time.sleep_ms(100) MediaManager.deinit() |
|
相关推荐
|
|
只有小组成员才能发言,加入小组>>
AI_cube训练模型得到了npy文件,没有kmodel文件
772 浏览 0 评论
请问K230 V3.0版本烧录固件和使用IDE到底是烧录哪个啊?
739 浏览 0 评论
443浏览 4评论
AI Cube进行yolov8n模型训练,创建项目目标检测时显示数据集目录下存在除标注和图片外的其他目录如何处理?
463浏览 3评论
autodl算力云在.pt转换onnx文件时正常,但onnx转.kmodel文件时报错,为什么?
552浏览 2评论
如何在大核rtt上把kd_mpi_vicap_start_stream三个摄像头各自出的流拼成一个流呢?
165浏览 2评论
564浏览 2评论
/9
小黑屋| 手机版| Archiver| 电子发烧友 ( 湘ICP备2023018690号 )
GMT+8, 2025-12-2 15:07 , Processed in 0.705093 second(s), Total 73, Slave 55 queries .
Powered by 电子发烧友网
© 2015 bbs.elecfans.com
关注我们的微信
下载发烧友APP
电子发烧友观察
版权所有 © 湖南华秋数字科技有限公司
电子发烧友 (电路图) 湘公网安备 43011202000918 号 电信与信息服务业务经营许可证:合字B2-20210191

淘帖
642
