更新时间: 试题数量: 购买人数: 提供作者:

有效期: 个月

章节介绍: 共有个章节

收藏
搜索
题库预览
项目名称:虚拟笔跟踪特定颜色物体导入必要的库import cv2import numpy as npimport timeimport os# 加载 HSV 阈值是否从磁盘读取load_from_disk = ( )if load_from_disk:# 从磁盘加载预先保存的 HSV 阈值hsv_value = np.load(r'./hus_value1.npy')print(hsv_value)# 打开摄像头cap = cv2.VideoCapture(0)# 设置摄像头分辨率cap.set (3,1280) # 宽度cap.set (4,720) # 高度# 定义形态学操作的核kernel = np.ones((5,5),np.uint8)# 初始化画布,用于在上面绘制canvas = None# 初始化 x1,y1 坐标(当前未使用)x1,y1 = 0,0# 噪声阈值noiseth = 800# 初始化视频写入器(None 表示尚未初始化)out = None# 视频编码器和输出视频文件的分辨率等参数fourcc = cv2.VideoWriter_fourcc (*'mp4v') # 输出视频格式为 mp4fps = int (cap.get (cv2.CAP_PROP_FPS)) # 帧率width = int (cap.get (cv2.CAP_PROP_FRAME_WIDTH)) # 宽度height = int (cap.get (cv2.CAP_PROP_FRAME_HEIGHT)) # 高度# 初始化视频写入器对象(初始为 None)out = Nonerecording = False # 标记是否正在录制while (1): # 无限循环,直到用户中断, frame = cap.read () # 读取摄像头帧frame = cv2.flip (frame, 1) # 水平翻转图像# 如果画布尚未初始化,则创建一个与帧相同大小的黑色图像if canvas is None:canvas = np.zeros_like(frame)# 将 BGR 图像转换为 HSV 图像hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)# 如果从磁盘加载 HSV 阈值if load_from_disk:# 加载下界和上界( ) = hsv_value[0]upper_range = hsv_value[1]else:# 否则使用自定义的 HSV 阈值范围2 = np.array ([134, 20, 204]) # 颜色的下界upper_range = np.array ([179, 255, 255]) # 颜色的上界# 创建颜色掩膜mask = cv2.inRange(hsv, lower_range, upper_range)# 形态学操作,去除噪声mask = cv2.erode (mask, kernel, iterations = 1) # 腐蚀操作mask = cv2.dilate (mask, kernel, iterations = 2) # 膨胀操作# 查找轮廓contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)# 确保存在轮廓且其面积大于噪声阈值if contours and cv2.contourArea(max(contours, key = cv2.contourArea)) > noiseth:# 找到面积最大的轮廓c = max(contours, key = cv2.contourArea)# 绘制检测到的轮廓边界框(或者模拟笔迹)( ) = cv2.boundingRect(c)# 初始化笔迹的起始点# 如果之前没有点(即第一次绘制或笔迹消失后重新开始),则将检测到的坐标设置为 x1,y1# 这在第一次写入或笔迹从视图中消失后再次写入时成立if x1 == 0 and y1 == 0:x1, y1 = x2, y2else:# 在画布上绘制从 x1,y1 到 x2,y2 的线# 使用红色([255,0,0])和 4 个像素的线宽canvas = cv2.line(canvas, (x1, y1), (x2, y2), [255, 0, 0], 4)# 绘制完线条后,新的点(x2,y2)成为之前的点(x1,y1)x1, y1 = x2, y2# 如果没有检测到轮廓,则将 x1,y1 重置为 0else:x1, y1 = 0, 0# 将画布和原始帧合并# 这会将画布上的线条叠加到原始帧上frame = cv2.add(frame, ( ) ) # 可选地将画布和帧水平堆叠并显示stacked = np.hstack((canvas, frame))cv2.imshow('VIRTUAL PEN', cv2.resize(stacked, None, fx=0.6, fy=0.6))# 等待按键输入k = cv2.waitKey(1) & 0xFF# 如果按下 ESC 键(ASCII 码为 27),则退出循环if k == 27:break# 当按下 'c' 键时清除画布# 这将重置画布,以便可以开始新的绘制if k == ord('c'):canvas = None# 如果正在录制,则将帧写入视频文件if recording and out is not None:out.write(frame)if recording and out is not None:out.write(frame)# 获取按键key = cv2.waitKey(int(1000 / fps))if key == ord ('q'): # 按下 'q' 键开始录制if not recording:# 创建视频写入器对象out = cv2.VideoWriter('output.mp4', ( )_, fps, (width, height))recording = Trueprint (' 开始录制...')elif key == ord ('s'): # 按下's' 键停止录制if recording:# 释放视频写入器对象并设置为 Noneout.release()out = Nonerecording = Falseprint (' 停止录制...')# 销毁所有 OpenCV 窗口cv2.destroyAllWindows()# 释放摄像头资源cap.release()
项目名称:实时物体尺寸测量 import cv2 import utlis webcam = False #读图 path = 'C:/Users/26982/Desktop/xm/09 Object Size Measurement/1.jpg' cap = cv2.VideoCapture(0) cap.set(10,160) cap.set(3,1920) cap.set(4,1080) scale = 3 wP = 210 *scale hP= 297 *scale while True: if webcam: success,img = cap.read() else: img = cv2.imread(1_) imgContours , conts = utlis.getContours(img,minArea=50000,filter=4) if len(conts) != 0: biggest = conts [0][2] #最大轮廓的拐点位置 #print(biggest) imgWarp = utlis.warpImg(img, biggest, wP,hP) imgContours2, conts2 = utlis.getContours(imgWarp,minArea=2000, filter=4,cThr=[50,50],draw = False) if len(conts) != 0: for obj in conts2: cv2.polylines(imgContours2,[obj[2]],True,(0,255,0),2) 2 = utlis.reorder(obj[2]) nW = round((utlis.findDis(nPoints[0][0]//scale,nPoints[1][0]//scale)/10),1) 3 = round((utlis.findDis(nPoints[0][0]//scale,nPoints[2][0]//scale)/10),1) #创建箭头 cv2.arrowedLine(imgContours2, (nPoints[0][0][0], nPoints[0][0][1]), (4, nPoints[1][0][1]),(255, 0, 255), 3, 8, 0, 0.05) cv2.arrowedLine(imgContours2, (nPoints[0][0][0], nPoints[0][0][1]), (nPoints[2][0][0], nPoints[2][0][1]),(255, 0, 255), 3, 8, 0, 0.05) x, y, w, h = obj[3] cv2.putText(imgContours2, '{}cm'.format(nW), (x + 30, y - 10), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1.5,(255, 0, 255), 2) cv2.putText(imgContours2, '{}cm'.format(nH), (x - 70, y + h // 2), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1.5,(255, 0, 255), 2) cv2.imshow('A4', 5_) img = cv2.resize(img,(0,0),None,0.5,0.5) cv2.imshow('Original',img) cv2.waitKey(1)
# 项目名称: 目标追踪 import cv2 import sys # 定义全局变量 # isTracking: 标记是否开始跟踪 # bbox: 跟踪的边界框,格式为 (x, y, width, height) # ok: 标记操作是否成功 # img2: 用于显示的当前帧 isTracking = False bbox = None ok = True img2 = None 1__ def on_mouse(event, x, y, flags, param): global img2, point1, point2, bbox, isTracking # 鼠标左键按下时记录起始点 if event == cv2.EVENT_LBUTTONDOWN: point1 = (x, y) # 在起始点画圆以标识 cv2.circle(img2, point1, 10, (0, 255, 0), 5) cv2.imshow('Tracking', img2) 2 elif event == cv2.EVENT_MOUSEMOVE and (flags & cv2.EVENT_FLAG_LBUTTON): cv2.rectangle(img2, point1, (x, y), (3_), 2) cv2.imshow('Tracking', img2) # 鼠标左键释放时记录结束点并初始化跟踪器 elif event == cv2.EVENT_LBUTTONUP: point2 = (x, y) cv2.rectangle(img2, point1, point2, (0, 0, 255), 2) cv2.imshow('Tracking', img2) # 如果起始点和结束点不同,则初始化跟踪区域 if point1 != point2: x1, y1 = min(point1[0], point2[0]), min(point1[1], point2[1]) width, height = abs(point1[0] - point2[0]), abs(point1[1] - point2[1]) bbox = (x1, y1, width, height) # 使用 tracker 初始化跟踪 ok = tracker.init(frame, bbox) isTracking = True # 主程序入口 if __name__ == '__main__': # 追踪器类型列表 tracker_types = ['BOOSTING', 'MIL', 'KCF', 'TLD', 'MEDIANFLOW', 'GOTURN', 'MOSSE', 'CSRT'] tracker_type = tracker_types [2] # 选择 KCF 追踪器 # 根据 OpenCV 版本创建追踪器实例 if int(cv2.__version__.split('.')[1]) < 3: tracker = cv2.Tracker_create(tracker_type) else: tracker = getattr(cv2, f'Tracker{tracker_type}_create')() # 打开摄像头 video = cv2.VideoCapture(r'C:\\Users\\Think\\Desktop/test.mp4') if not video.isOpened(): print (\\'无法打开视频\\') sys.exit() # 创建窗口并绑定鼠标回调函数 cv2.namedWindow('Tracking') cv2.setMouseCallback('Tracking' on_mouse) while True: # 读取视频帧 ok, frame = video.read() if not ok: break img2 = frame # 如果已经开始跟踪,则更新跟踪器 if isTracking: # 计时开始 timer = cv2.getTickCount() # 更新跟踪器 ok, __4 = tracker.update(frame) # 计算帧率 fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer) if ok: # 根据跟踪结果绘制矩形框 p1 = (int(bbox[0]), int(bbox[1])) p2 = (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3])) cv2.rectangle(frame, p1, p2, (255,0, 0), 2) # 在视频帧上显示跟踪器类型和帧率 cv2.putText(frame, f\\\"{5} Tracker\\\", (100, 20), cv2.FONT_HERSHEY_SIMPLEX,0.75,(50,170, 50), 2) cv2.putText(frame, f\\\"FPS: {int(fps)}\\\", (100, 50), cv2.FONT_HERSHEY_SIMPLEX,0.75, (50,170, 50), 2) else: # 如果跟踪失败,则在视频帧上显示失败信息 cv2.putText(frame, \\\"Tracking failure detected\\\", (100, 80), cv2.FONT_HERSHEY_SIMPLEX,0.75, (0,0, 255), 2) # 显示视频帧 cv2.imshow('Tracking', frame) # 按 ESC 键退出循环 if cv2.waitKey(1) & 0xFF == 27: break # 释放摄像头资源 video.release() # 销毁所有窗口 cv2.destroyAllWindows()
# 项目名称:贪吃蛇 import math import random import cvzone import cv2 import numpy as np from cvzone.HandTrackingModule import HandDetector cap = cv2.VideoCapture(0) width = 1300 height = 800 cap.set (3, width) # 设置宽度 cap.set (4, height) # 设置高度 if not cap.isOpened(): print (\\无法打开摄像头\\\") exit() detector = HandDetector(detectionCon=0.8, maxHands=1) class SnakeGameClass: def __init__(self, (1)____): self.points = [] # 蛇的所有点 self.lengths = [] # 各点之间的距离 self.currentLength = 0 # 蛇的总长度 self.allowedLength = 150 # 允许的最大长度 self.previousHead = 0, 0 # 前一个头部位置 self.imgFood = (1)____ # 图片食物 if self.imgFood.shape[2] != 4: self.imgFood = cv2.cvtColor(self.imgFood, cv2.COLOR_BGR2BGRA) self.hFood, self.wFood, _ = self.imgFood.shape self.foodPoint = 0, 0 self.randomFoodLocation() self.score = 0 # 2____ self.gameOver = False def randomFoodLocation(self): self.foodPoint = (random.randint(300, 1000), random.randint(300, 600)) def update(self, imgMain, currentHead): font = cv2.FONT_HERSHEY_COMPLEX # 更改字体 textColor = (255,100, 168)[::-1] if self.gameOver: cvzone.putTextRect(imgMain, \\\"Game Over\\\", [300, 400], scale=3, thickness=3, offset=20, font=font, colorR=textColor) cvzone.putTextRect(imgMain, f'Your Score: {self.score}', [300, 550], scale=3, thickness=3, offset=20, font=font, colorR=textColor) else: px, py = self.previousHead cx, cy = currentHead self.points.append([cx, cy]) distance = math.hypot (cx - px, cy - py) # 计算两点之间的距离 self.lengths.append(distance) self.currentLength += distance self.previousHead = cx, cy # 减少长度 if self.currentLength > self.allowedLength: for i, length in enumerate(self.lengths): self.currentLength -= length self.lengths.pop(i) self.points.pop(i) if self.currentLength <= self.allowedLength: break rx, ry = self.foodPoint # 3____ if rx - self.wFood // 2 < cx < rx + self.wFood // 2 and <br> ry - self.hFood // 2 < cy < ry + self.hFood // 2: self.randomFoodLocation() self.allowedLength += 50 self.score += 1 print(self.score) # 画蛇 if self.points: for i, point in enumerate(self.points): if i != 0: # 红色身体 cv2.line(imgMain, tuple(self.points[i - 1]), tuple(self.points[i]), (0,0, 255), 20) cv2.circle(imgMain, tuple(self.points[-1]), 15, (255,0, 0), cv2.FILLED) # 画食物 imgMain = cvzone.overlayPNG(imgMain, self.imgFood, (rx - self.wFood // 2, ry - self.hFood // 2)) cvzone.putTextRect(imgMain, f'Score: {self.score}', [50, 80], scale=2, thickness=2, offset=10, font=font, colorR=(255,76,108)[::-1]) # 检查碰撞 pts = np.array(self.points[:-2], np.int32) pts = pts.reshape((-1,1, 2)) cv2.polylines(imgMain, [pts], False, (0,255, 0), 5) minDist = cv2.pointPolygonTest(pts, (cx, cy), True) if -1 <= minDist <= 1: self.gameOver = True self.points = [] # 清空蛇的所有点 self.lengths = [] # 清空点之间的距离 self.currentLength = 0 # 重置蛇的总长度 self.allowedLength = 150 # 重置允许的最大长度 self.previousHead = 0, 0 # 重置前一个头部位置 self.randomFoodLocation() return imgMain if __name__ == '__main__': food = cv2.imread('./food.png', cv2.IMREAD_UNCHANGED) food = cv2.resize(food, (60, 60)) # 传入图片,实例化对象,对象名为 game game = (4)____(food) while True: success, img = cap.read() if not success: print (\\\"无法接收帧 (stream end?). Exiting ...\\\") break # 图片反转,0:x 1: y img = cv2.flip(img, 1) hands, img = detector.findHands(img, flipType=False) if hands: lmList = hands[0]['lmList'] pointIndex = lmList[8][0:2] print(lmList[8][0:2]) img = game.update(img, pointIndex) cv2.imshow(\\\"snake game\\\", img) key = cv2.waitKey(1) if key == ord('r'): # 按 r 重新开始游戏 game.gameOver = False # 5____ game.score = 0 if key == 27: # 按 Esc 退出游戏 break cap.release() cv2.destroyAllWindows()
1