摄像头拍摄散放多个物料 物料是同一种物料, opencv 获取图片中最中心三个物料中心坐标。
6条回答 默认 最新
- prince_zxill 2022-09-17 19:00关注
看看这个代码行不行:
# coding:UTF-8 import cv2 import numpy as np class Findposition: def __init__(self,path): #获取图片 self.img=cv2.imread(path) self.gray=cv2.cvtColor(self.img,cv2.COLOR_BGR2GRAY) self.hsv=cv2.cvtColor(self.img,cv2.COLOR_BGR2HSV) #提取黑色的区域 def Get_black(self): #get black area low_black=np.array([0,0,0]) high_black=np.array([100,100,100]) mask=cv2.inRange(self.img,low_black,high_black) black=cv2.bitwise_and(self.hsv,self.hsv,mask=mask) return black #将黑色区域进行二值化处理 def Get_contour(self): #change to gray black=self.Get_black() black_gray=cv2.cvtColor(black,cv2.COLOR_HSV2BGR) black_gray=cv2.cvtColor(black_gray,cv2.COLOR_BGR2GRAY) #binaryzation _, thresh=cv2.threshold(black_gray,10,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) img_morph=cv2.morphologyEx(thresh,cv2.MORPH_OPEN,(3,3)) cv2.erode(img_morph,(3,3),img_morph,iterations=2) cv2.dilate(img_morph,(3,3),img_morph,iterations=2) return img_morph #获取中心区域轮廓及坐标 def Find_contour(self,img): img_cp=img.copy() cnts,_=cv2.findContours(img_cp,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) cnt_second=sorted(cnts,key=cv2.contourArea,reverse=True)[1] box =cv2.minAreaRect(cnt_second) return np.int0(cv2.cv.BoxPoints(box)) #绘制轮廓 def Draw_contour(self,points): mask=np.zeros(self.gray.shape,np.uint8) cv2.drawContours(mask,[points],-1,255,2) return mask #获取中心位置 def Get_center(self,points): p1x,p1y=points[0,0],points[0,1] p3x,p3y=points[2,0],points[2,1] center_x,center_y=(p1x+p3x)/2,(p1y+p3y)/2 center=(center_x,center_y) return center #绘制中心点 def Draw_center(self,center,mask): cv2.circle( mask,center,1,(255,255,255),2) return mask #主函数 def main_process(self): morph=self.Get_contour() black=self.Get_black() points=self.Find_contour(morph) mask=self.Draw_contour(points) center=self.Get_center(points) draw_center=self.Draw_center(center,mask) center_x,center_y=self.Get_center(points) print(center_x,center_y) cv2.imshow('black',black) cv2.imshow('morph',morph) cv2.imshow('img',self.img) cv2.imshow('contour',draw_center) cv2.waitKey(0) if __name__== '__main__' : path='C:\Users\KaiyuanCao\Desktop\sample.jpg' d = Findposition(path) d.main_process()
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报