zhoutao 6 months ago
parent 71ed9b8b50
commit e59377dcee

@ -1,72 +1,84 @@
import cv2
import numpy as np
def init_camera():
global cap
def main():
# 初始化摄像头
cap = cv2.VideoCapture(0)
def select_color_area(frame):
global color_selected, greenLower, greenUpper
# 用于标记是否已经选择颜色区域的变量
color_selected = False
color_lower = None
color_upper = None
while True:
# 从摄像头读取一帧
ret, frame = cap.read()
if not ret:
break
# 如果还没有选择颜色区域,显示当前帧并允许用户选择
if not color_selected:
cv2.imshow('Select color area', frame)
# 用户按下'c'键时截取当前帧并允许用户选择ROI
if cv2.waitKey(1) & 0xFF == ord('c'):
# 转换到HSV
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
roi = cv2.selectROI('Select color area', hsv)
if roi != (0, 0, 0, 0):
# 计算ROI的平均颜色
roi_hsv = hsv[int(roi[1]):int(roi[1] + roi[3]), int(roi[0]):int(roi[0] + roi[2])]
color_mean = np.mean(roi_hsv, axis=(0, 1))
color_mean = np.uint8(color_mean)
greenLower = np.array([max(color_mean[0] - 10, 0), 50, 50])
greenUpper = np.array([min(color_mean[0] + 10, 179), 255, 255])
print(f"Selected color: {color_mean}, Lower bound: {greenLower}, Upper bound: {greenUpper}")
# 创建颜色范围
# color_range = 10
color_lower = np.array(
[max(color_mean[0] - 30, 0), max(color_mean[1] - 60, 0), max(color_mean[2] - 55, 0)])
color_upper = np.array(
[min(color_mean[0] + 10, 179), 255, 255])
# print(f"Selected color: {color_mean}, Lower bound: {greenLower}, Upper bound: {greenUpper}")
color_selected = True
cv2.destroyAllWindows()
cv2.destroyWindow('Select color area')
else:
print("No ROI selected. Exiting...")
cv2.destroyAllWindows()
return False
return True
break
def track_color(frame, greenLower, greenUpper):
else:
# 颜色区域已选择,进行颜色追踪
# 将BGR图像转换为HSV
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, greenLower, greenUpper)
# 创建掩码
mask = cv2.inRange(hsv, color_lower, color_upper)
# 应用开运算和闭运算去除噪声
kernel = np.ones((5, 5), np.uint8)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
# 查找轮廓
contours, _ = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 遍历轮廓,画出边界框
for contour in contours:
if cv2.contourArea(contour) > 200:
if cv2.contourArea(contour) > 300:
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
print(color_lower, color_upper)
return frame, mask
def main():
init_camera()
color_selected = False
while True:
ret, frame = cap.read()
if not ret:
break
if not color_selected:
if not select_color_area(frame):
break
else:
frame, mask = track_color(frame, greenLower, greenUpper)
# 显示原图和结果图像
cv2.imshow('Original', frame)
cv2.imshow('Mask', mask)
# 按'q'键退出循环
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放资源并关闭所有窗口
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
if __name__ == '__main__':
main()

@ -6,12 +6,12 @@ from threading import Thread
# 颜色的HSV阈值
color_hsv_ranges = {
'blue': {'lower': np.array([100, 150, 50], dtype=np.uint8),
'upper': np.array([140, 255, 255], dtype=np.uint8)},
'green': {'lower': np.array([35, 46, 120], dtype=np.uint8),
'upper': np.array([60, 255, 255], dtype=np.uint8)},
'red': {'lower': np.array([0, 116, 164], dtype=np.uint8),
'upper': np.array([180, 255, 255], dtype=np.uint8)},
'blue': {'lower': np.array([80, 170, 192], dtype=np.uint8),
'upper': np.array([120, 255, 255], dtype=np.uint8)},
'green': {'lower': np.array([25, 50, 147], dtype=np.uint8),
'upper': np.array([55, 255, 255], dtype=np.uint8)},
'red': {'lower': np.array([0, 112, 194] , dtype=np.uint8),
'upper': np.array([13, 255, 255], dtype=np.uint8)},
'custom': {'lower': np.array([0, 0, 0], dtype=np.uint8),
'upper': np.array([180, 255, 255], dtype=np.uint8)}
}
@ -79,6 +79,7 @@ def exit_app():
global running, cap
running = False
cap.release()
cv2.destroyAllWindows()
root.quit()
def initialize_gui():

@ -1,3 +1,34 @@
import Color_tracking
import PyQt6
Color_tracking.main()
import Area_tracking
import sys
from PyQt6.QtWidgets import QApplication, QWidget, QPushButton
def quit_app():
sys.exit(app.quit())
def main1():
print("main1 function called")
def main2():
print("main2 function called")
app = QApplication(sys.argv)
widget = QWidget()
widget.resize(300, 200)
button1 = QPushButton('自选单颜色追踪', widget)
button1.move(50, 50)
button1.clicked.connect(Color_tracking.main)
button2 = QPushButton('自选区域颜色追踪', widget)
button2.move(50, 100)
button2.clicked.connect(Area_tracking.main)
quit_button = QPushButton('退出', widget)
quit_button.move(150, 50)
quit_button.clicked.connect(quit_app)
widget.show()
sys.exit(app.exec())

Loading…
Cancel
Save