SoFunction
Updated on 2024-11-13

50 lines of Python code for object color recognition and tracking in video (must be in red)

At present, computer vision (CV) and natural language processing (NLP) and speech recognition are listed as the three major hotspot directions of artificial intelligence, and objectdetection in computer vision has a wide range of applications, such as automated driving, video surveillance, industrial quality inspection, medical diagnosis and other scenarios.

The fundamental task of target detection is to extract the target of interest from a picture or video, and target recognition can be based on color, texture, and shape. Among them, the color attribute is widely used and relatively easy to implement. Below is to share with you a small experiment I did --- through OpenCV's Python interface to achieve color recognition and tracking from video.

Here is our complete code implementation (debugged and running):

import numpy as np
import cv2
font = cv2.FONT_HERSHEY_SIMPLEX
lower_green = ([35, 110, 106]) # Green range low threshold
upper_green = ([77, 255, 255]) # Green range high threshold
lower_red = ([0, 127, 128]) # Red range low threshold
upper_red = ([10, 255, 255]) # Red range high threshold
# Need more colors, go to Baidu for HSV thresholds!
# cap = ('1.mp4') # open video file
cap = (0)# Turn on the USB camera
if (()): # The video opened successfully
 flag = 1
else:
 flag = 0
num = 0
if (flag):
 while (True):
 ret, frame = () # Read a frame
 
 if ret == False: # Failed to read the frame
  break
 hsv_img = (frame, cv2.COLOR_BGR2HSV)
 mask_green = (hsv_img, lower_green, upper_green) # Censored by color range
 mask_red = (hsv_img, lower_red, upper_red) 
 # Censored by color range
 mask_green = (mask_green, 7) # Median filtering
 mask_red = (mask_red, 7) # Median filtering
 mask = cv2.bitwise_or(mask_green, mask_red)
 mask_green, contours, hierarchy = (mask_green, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
 mask_red, contours2, hierarchy2 = (mask_red, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

 for cnt in contours:
  (x, y, w, h) = (cnt)
  (frame, (x, y), (x + w, y + h), (0, 255, 255), 2)
  (frame, "Green", (x, y - 5), font, 0.7, (0, 255, 0), 2)

 for cnt2 in contours2:
  (x2, y2, w2, h2) = (cnt2)
  (frame, (x2, y2), (x2 + w2, y2 + h2), (0, 255, 255), 2)
  (frame, "Red", (x2, y2 - 5), font, 0.7, (0, 0, 255), 2)
 num = num + 1
 ("dection", frame)
 ("imgs/%"%num, frame)
 if (20) & 0xFF == 27:
  break
(0)
()

As shown in the figure, we will detect the red area

The final rendering:

summarize

The above is a small introduction to the 50 lines of Python code to achieve object color recognition and tracking in the video, I hope to help you, if you have any questions please leave me a message, I will reply to you in time. I would also like to thank you very much for your support of my website!
If you find this article helpful, please feel free to reprint it, and please note the source, thank you!