sdjkabhkgd

import cv2# 打开摄像头
cap = cv2.VideoCapture(0)while True:# 读取图像帧ret, frame = cap.read()# 将图像帧转换为HSV颜色空间hsv_image = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)# 选择红点的颜色范围red_lower = (0, 100, 100)red_upper = (10, 255, 255)# 创建颜色掩码red_mask = cv2.inRange(hsv_image, red_lower, red_upper)# 寻找红点red_dot_coordinates = cv2.findNonZero(red_mask)# 计算红点的中心坐标if red_dot_coordinates is not None:M = cv2.moments(red_mask)if M["m00"] != 0:red_dot_center_x = int(M["m10"] / M["m00"])red_dot_center_y = int(M["m01"] / M["m00"])red_dot_center = [red_dot_center_x, red_dot_center_y]else:red_dot_center = []else:red_dot_center = []# 将图像转换为灰度图像gray_image = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)# 进行边缘检测edges = cv2.Canny(gray_image, 50, 150)# 寻找轮廓contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)# 找到矩形轮廓(假设正方形是最大的矩形轮廓)max_area = 0target_contour = Nonefor contour in contours:area = cv2.contourArea(contour)if area > max_area:max_area = areatarget_contour = contour# 如果找到正方形轮廓,则进行裁剪if target_contour is not None:# 获取裁剪区域的边界框x, y, w, h = cv2.boundingRect(target_contour)# 在图像上绘制矩形轮廓(可选)cv2.drawContours(frame, [target_contour], -1, (0, 255, 0), 2)# 裁剪图像,只保留感兴趣的正方形区域cropped_frame = frame[y:y + h, x:x + w]# 绘制红点if red_dot_center:cv2.circle(frame, tuple(red_dot_center), 5, (0, 0, 255), -1)# 显示实时图像cv2.imshow("Real-time Image", frame)# 按下'q'键退出循环if cv2.waitKey(1) & 0xFF == ord('q'):break


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部