python opencv运用滑块实现七个颜色识别功能
时间: 2023-08-03 09:08:55 浏览: 75
好的,下面是 Python 和 OpenCV 实现七个颜色识别功能的代码,同时使用 PyQt5 库实现了滑块的控制:
```python
import cv2
import numpy as np
from PyQt5.QtWidgets import QApplication, QWidget, QSlider, QVBoxLayout
from PyQt5.QtCore import Qt
# 创建窗口和滑块控件
app = QApplication([])
window = QWidget()
slider1 = QSlider(Qt.Horizontal)
slider2 = QSlider(Qt.Horizontal)
slider3 = QSlider(Qt.Horizontal)
slider4 = QSlider(Qt.Horizontal)
slider5 = QSlider(Qt.Horizontal)
slider6 = QSlider(Qt.Horizontal)
slider7 = QSlider(Qt.Horizontal)
layout = QVBoxLayout()
layout.addWidget(slider1)
layout.addWidget(slider2)
layout.addWidget(slider3)
layout.addWidget(slider4)
layout.addWidget(slider5)
layout.addWidget(slider6)
layout.addWidget(slider7)
window.setLayout(layout)
# 打开摄像头
cap = cv2.VideoCapture(0)
while True:
# 读取每一帧图像
ret, frame = cap.read()
if not ret:
break
# 转换颜色空间
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# 进行七种颜色的二值化
lower_red = np.array([slider1.value(), slider2.value(), slider3.value()])
upper_red = np.array([slider1.value() + 10, slider2.value() + 10, slider3.value() + 10])
mask_red = cv2.inRange(hsv, lower_red, upper_red)
lower_green = np.array([slider4.value(), slider5.value(), slider6.value()])
upper_green = np.array([slider4.value() + 10, slider5.value() + 10, slider6.value() + 10])
mask_green = cv2.inRange(hsv, lower_green, upper_green)
lower_blue = np.array([slider7.value(), 100, 100])
upper_blue = np.array([slider7.value() + 10, 255, 255])
mask_blue = cv2.inRange(hsv, lower_blue, upper_blue)
lower_yellow = np.array([20, 100, 100])
upper_yellow = np.array([30, 255, 255])
mask_yellow = cv2.inRange(hsv, lower_yellow, upper_yellow)
lower_orange = np.array([10, 100, 100])
upper_orange = np.array([20, 255, 255])
mask_orange = cv2.inRange(hsv, lower_orange, upper_orange)
lower_purple = np.array([130, 100, 100])
upper_purple = np.array([140, 255, 255])
mask_purple = cv2.inRange(hsv, lower_purple, upper_purple)
lower_cyan = np.array([80, 100, 100])
upper_cyan = np.array([90, 255, 255])
mask_cyan = cv2.inRange(hsv, lower_cyan, upper_cyan)
# 对每一帧图像进行颜色识别
for mask, color in zip([mask_red, mask_green, mask_blue, mask_yellow, mask_orange, mask_purple, mask_cyan],
[(0, 0, 255), (0, 255, 0), (255, 0, 0), (0, 255, 255), (0, 128, 255), (128, 0, 128), (255, 255, 0)]):
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
area = cv2.contourArea(contour)
if area > 100:
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(frame, (x, y), (x+w, y+h), color, 2)
# 显示识别结果
cv2.imshow('frame', frame)
if cv2.waitKey(1) == ord('q'):
break
# 关闭窗口和摄像头
cv2.destroyAllWindows()
cap.release()
# 运行 PyQt5 应用程序
window.show()
app.exec_()
```
这个程序中,我们使用了 `numpy` 库中的 `array` 函数来创建颜色的阈值范围,使用 `cv2.inRange` 函数将图像二值化,使用 `cv2.findContours` 函数找到每个颜色的轮廓,使用 `cv2.rectangle` 函数在图像上绘制矩形框。
注意:程序中的颜色阈值范围是根据摄像头拍摄的实际情况进行调整的,具体实现可能需要根据实际情况进行修改和调整。
阅读全文