import cv2
import numpy as np
import matplotlib.pyplot as plt
min_area_px = 30 # حذف مناطق کوچک
# مقدار آستانه قرمز کم شده تا مناطق کمرنگ هم شناسایی شوند
red_threshold_low = 80
cap = cv2.VideoCapture(0)
plt.ion()
fig, ax = plt.subplots()
while True:
ret, frame = cap.read()
if not ret:
print("دوربین باز نشد")
break
frame_small = cv2.resize(frame, (320, 240))
output = frame_small.copy()
# تبدیل به HSV برای شناسایی بهتر رنگ قرمز
hsv = cv2.cvtColor(frame_small, cv2.COLOR_BGR2HSV)
# ماسک قرمز با محدوده گستردهتر
lower_red1 = np.array([0, 30, 30])
upper_red1 = np.array([15, 255, 255])
lower_red2 = np.array([160, 30, 30])
upper_red2 = np.array([180, 255, 255])
mask1 = cv2.inRange(hsv, lower_red1, upper_red1)
mask2 = cv2.inRange(hsv, lower_red2, upper_red2)
red_mask = cv2.bitwise_or(mask1, mask2)
# پیدا کردن مناطق قرمز
num_labels, labels_im = cv2.connectedComponents(red_mask)
for label in range(1, num_labels):
ys, xs = np.where(labels_im == label)
if len(xs) == 0:
continue
area = len(xs)
if area < min_area_px:
continue
x_center = int(xs.mean())
y_center = int(ys.mean())
# نوشتن متن Red
text = "Red"
cv2.putText(output, text, (x_center-10, y_center),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 1)
# خط باریک سبز دور منطقه
region_mask = np.zeros(frame_small.shape[:2], np.uint8)
region_mask[ys, xs] = 255
contours, _ = cv2.findContours(region_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(output, contours, -1, (0,255,0), 1)
# مناطق غیر قرمز → No
no_mask = cv2.bitwise_not(red_mask)
num_labels_no, labels_no = cv2.connectedComponents(no_mask)
for label in range(1, num_labels_no):
ys, xs = np.where(labels_no == label)
if len(xs) == 0:
continue
area = len(xs)
if area < min_area_px:
continue
x_center = int(xs.mean())
y_center = int(ys.mean())
text = "No"
cv2.putText(output, text, (x_center-10, y_center),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 1)
# خط باریک آبی دور منطقه
region_mask = np.zeros(frame_small.shape[:2], np.uint8)
region_mask[ys, xs] = 255
contours, _ = cv2.findContours(region_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(output, contours, -1, (255,0,0), 1)
ax.clear()
ax.imshow(cv2.cvtColor(output, cv2.COLOR_BGR2RGB))
ax.axis("off")
plt.title("عالی اول - Red / No Detection")
plt.pause(1)
cap.release()
plt.ioff()
plt.show()