Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize Color-based Target recognition by Python+OpenCV

2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces how to achieve color-based target recognition with Python+OpenCV. The content is very detailed. Interested friends can use it for reference. I hope it will be helpful to you.

Task

Let the camera recognize the balloon in the field of view and return the center coordinates of each balloon.

Because the site is fixed and the background is single, it saves a lot of operation and processing. So there are two solutions: the first is to extract the contour based on the shape of the balloon, as long as it is a closed ellipse or circle, it is considered to be the target object; the second is based on the color of the balloon, as long as it matches the color of the target object.

Because the camera is installed on the quadruped robot (its task is to prick the balloon), it will not be recognized if it moves within the camera's field of view when the balloon is not a closed ellipse or circle, coupled with the shadow caused by the site lighting, it is found in the preliminary practice that the balloon after image processing is not necessarily closed spherical. So this method was rejected by me.

So I adopted the second method, which is roughly as follows:

First of all, the image is processed by morphology, specifically, the grayscale image read is filtered, the image is transformed into HSV image, and then the corrosion operation is carried out. Then the target color is identified and extracted. Then the outline of the image is extracted, the contour is filtered out to form a smaller object, and the remaining object is regarded as the target. The next step is to draw the outer rectangle of the target (unnecessary, for debugging. And, of course, for handsome visual effects. Finally, the center point of the target is calculated, returned to the center point, and drawn on the graph.

Without saying much, let's take a look at the specific code implementation.

The main code import cv2#import matplotlib.pyplot as pltimport numpy as np# defines a function def cv_show (name,img): cv2.imshow (name,img) cv2.waitKey (0) cv2.destroyAllWindows () # defines a function for morphological processing def good_thresh_img (img): gs_frame = cv2.GaussianBlur (img, (5,5)) 0) # Gaussian filtering hsv = cv2.cvtColor (gs_frame, cv2.COLOR_BGR2HSV) # converted into HSV image erode_hsv = cv2.erode (hsv, None, iterations=2) return erode_hsv# defines a function def select_color_img (target_color,img): for i in target_color: mask=cv2.inRange (erode_hsv) that identifies the target color and processes it Color_ disti ['Lower'], color_ disti [' Upper']) if (i==target_color [0]): inRange_hsv=cv2.bitwise_and (erode_hsv,erode_hsv,mask = mask) cv_show ('res',inRange_hsv) # unnecessary Used to debug else: inRange_hsv1=cv2.bitwise_and (erode_hsv,erode_hsv,mask = mask) cv_show ('res1',inRange_hsv1) # unnecessary, used to debug inRange_hsv=cv2.add (inRange_hsv,inRange_hsv1) cv_show (' res2',inRange_hsv) # unnecessary Define a function def extract_contour (img) for debugging return inRange_hsv# to extract contours: inRange_gray = cv2.cvtColor (final_inRange_hsv,cv2.COLOR_BGR2GRAY) contours,hierarchy = cv2.findContours (inRange_gray,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE) return contours # define a function def find_target (contours) to find the target and draw the circumscribed rectangle Draw_img): for c in contours: if cv2.contourArea (c)

< 2000: #过滤掉较面积小的物体 continue else: target_list.append(c) #将面积较大的物体视为目标并存入目标列表 for i in target_list: #绘制目标外接矩形 rect = cv2.minAreaRect(i) box = cv2.boxPoints(rect) cv2.drawContours(draw_img, [np.int0(box)], -1, (0, 255, 255), 2) return draw_img#定义一个绘制中心点坐标的函数def draw_center(target_list,draw_img): for c in target_list: M = cv2.moments(c) #计算中心点的x、y坐标 center_x = int(M['m10']/M['m00']) center_y = int(M['m01']/M['m00']) print('center_x:',center_x) #打印(返回)中心点的x、y坐标 print('center_y:',center_y) cv2.circle(draw_img,(center_x,center_y),7,128,-1)#绘制中心点 str1 = '(' + str(center_x)+ ',' +str(center_y) +')' #把坐标转化为字符串 cv2.putText(draw_img,str1,(center_x-50,center_y+40),cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,0),2,cv2.LINE_AA)#绘制坐标点位 return draw_img###主函数部分#创建颜色字典color_dist = {'red': {'Lower': np.array([0, 60, 60]), 'Upper': np.array([6, 255, 255])}, 'yellow': {'Lower': np.array([15, 160, 50]), 'Upper': np.array([35, 255, 255])}, 'green': {'Lower': np.array([50, 50, 50]), 'Upper': np.array([130, 255, 255])}, }#目标颜色target_color = ['green','yellow']#创建目标列表target_list=[]img = cv2.imread(r'D:lesson\balloom.jpg',cv2.COLOR_BGR2RGB) #读入图像(直接读入灰度图)draw_img = img.copy() #为保护原图像不被更改而copy了一份,下面对图像的修改都是对这个副本进行的erode_hsv = good_thresh_img(img)final_inRange_hsv = select_color_img(target_color,erode_hsv)contours = extract_contour(final_inRange_hsv)draw_img = find_target(contours,draw_img)final_img = draw_center(target_list,draw_img)cv_show('final_img',final_img)效果展示 颜色提取效果:

The effect of drawing the circumscribed rectangle and center point:

On how to achieve Python+OpenCV color-based target recognition is shared here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 206

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report