我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用cv2.RETR_TREE。
def diff_rect(img1, img2, pos=None): """find counters include pos in differences between img1 & img2 (cv2 images)""" diff = cv2.absdiff(img1, img2) diff = cv2.GaussianBlur(diff, (3, 3), 0) edges = cv2.Canny(diff, 100, 200) _, thresh = cv2.threshold(edges, 0, 255, cv2.THRESH_BINARY) contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) if not contours: return None contours.sort(key=lambda c: len(c)) # no pos provide, just return the largest different area rect if pos is None: cnt = contours[-1] x0, y0, w, h = cv2.boundingRect(cnt) x1, y1 = x0+w, y0+h return (x0, y0, x1, y1) # else the rect should contain the pos x, y = pos for i in range(len(contours)): cnt = contours[-1-i] x0, y0, w, h = cv2.boundingRect(cnt) x1, y1 = x0+w, y0+h if x0 <= x <= x1 and y0 <= y <= y1: return (x0, y0, x1, y1)
def classify(img): cimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img2 = cv2.medianBlur(cimg, 13) ret, thresh1 = cv2.threshold(cimg, 100, 120, cv2.THRESH_BINARY) t2 = copy.copy(thresh1) x, y = thresh1.shape arr = np.zeros((x, y, 3), np.uint8) final_contours = [] image, contours, hierarchy = cv2.findContours(t2, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) #cv2.imshow('image', image) #k = cv2.waitKey(0) for i in range(len(contours)): cnt = contours[i] if cv2.contourArea(cnt) > 3000 and cv2.contourArea(cnt) < 25000: cv2.drawContours(img, [cnt], -1, [0, 255, 255]) cv2.fillConvexPoly(arr, cnt, [255, 255, 255]) final_contours.append(cnt) #cv2.imshow('arr', arr) #k = cv2.waitKey(0) return arr
def diagContour(image): #Find contours in the image the first and last returns dont matter so the _ is just a placeholder to ignore them _, contours, _ = cv2.findContours(image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) #The contouring operation does some weird stuff to the image so this line just fills the whole thing with black image.fill(0) boundingRect = [] firstFail = [] #Loops through all contours bigger than minArea pixels. That number is tweakable and determined by testing for j in [i for i in contours if cv2.contourArea(i) > minArea]: #br is a (list/tuple)? of the form x, y, width, height where (x,y) is the (top/bottom)? (left/right)? corner br = cv2.boundingRect(j) if(abs(br[2]/br[3] - INDASPECT) < indAspectTol and cv2.contourArea(j)/(br[2]*br[3]) > covTol): boundingRect.append(br) else: firstFail.append([br, br[2]/br[3], cv2.contourArea(j)/(br[2]*br[3])]) secondRound = [] for x in range(0, len(boundingRect)): for y in range(x+1, len(boundingRect)): i = boundingRect[x] j = boundingRect[y] secondRound.append([(x,y,i,j), (abs(i[1]-j[1]), i[3]/2), abs(i[0]-j[0])/i[1]]) for x in secondRound: if(x[1][0] < x[1][1] and x[2] - GRPASPECT < grpAspectTol): return [x[0][2], x[0][3]] return None;
def GetImageContour(self): thresholdImage = self.__convertImagetoBlackWhite() #B & W with adaptive threshold thresholdImage = cv.Canny(thresholdImage, 100, 200) #Edges by canny edge detection thresholdImage, contours, hierarchy = cv.findContours( thresholdImage, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE) self.Contours = contours # uncomment this to see the contours on the image # cv2.drawContours(thresholdImage, contours, -1, (0,255,0), 3) # patternFindingObj=PatternFinding() # areas= [cv.contourArea(contour) for contour in contours] # for index in xrange(len(contours)): # IsPattern=self.IsPossibleQRContour(index) # if IsPattern is True: # x,y,w,h=cv.boundingRect(contours[index]) # cv.rectangle(self.imageOriginal,(x,y),(x+w,y+h),(0,0,255),2) # cv.imshow("hello",self.imageOriginal) # maxAreaIndex=np.argmax(areas) # x,y,w,h=cv.boundingRect(contours[maxAreaIndex]) # cv.rectangle(self.image2,(x,y),(x+w,y+h),(0,255,0),2) # cv.imshow("hello",self.imageOriginal) # cv.waitKey(0) #cv.destroyAllWindows() contour_group = (thresholdImage, contours, hierarchy) return contour_group
def imgSeg_contour(img, b,g,r, per): lower = np.array([0, 0, 0]) upper = np.array([b,g,r]) shapeMask = cv2.inRange(img, lower, upper) #http://stackoverflow.com/questions/27746089/python-computer-vision-contours-too-many-values-to-unpack _, cnts, hierarchy = cv2.findContours(shapeMask.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:4] for c in cnts: peri = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, per * peri, True) ### 0.04 ### if (len(approx) >= 4) and (len(approx) < 6): break return approx
def shapeFiltering(img): contours = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[0] if len(contours) == 0: print "shapeFiltering: Error, no contours found" return 1 good_shape = [] for c in contours: x,y,w,h = cv2.boundingRect(c) #if h == 0: # continue ratio = w / h ratio_grade = ratio / (TMw / TMh) if 0.2 < ratio_grade < 1.8: good_shape.append(c) return good_shape
def EdgeDetection(img): img = cv2.fastNlMeansDenoising(img,None,3,7,21) _,img = cv2.threshold(img,30,255,cv2.THRESH_TOZERO) denoise_img = img laplacian = cv2.Laplacian(img,cv2.CV_64F) sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=5) # x sobely = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=3) # y canny = cv2.Canny(img,100,200) contour_image, contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) return {"denoise":denoise_img,"laplacian":laplacian,"canny":canny,"sobely":sobely,"sobelx":sobelx,"contour":contour_image} # GrayScale Image Convertor # https://extr3metech.wordpress.com
def find_contour(self, img_src, Rxmin, Rymin, Rxmax, Rymax): cv2.rectangle(img_src, (Rxmax, Rymax), (Rxmin, Rymin), (0, 255, 0), 0) crop_res = img_src[Rymin: Rymax, Rxmin:Rxmax] grey = cv2.cvtColor(crop_res, cv2.COLOR_BGR2GRAY) _, thresh1 = cv2.threshold(grey, 127, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) cv2.imshow('Thresh', thresh1) contours, hierchy = cv2.findContours(thresh1.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) # draw contour on threshold image if len(contours) > 0: cv2.drawContours(thresh1, contours, -1, (0, 255, 0), 3) return contours, crop_res # Check ConvexHull and Convexity Defects
def process_img(img): original_image=img processed_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) processed_img = cv2.Canny(processed_img, threshold1=200, threshold2=300) processed_img = cv2.GaussianBlur(processed_img, (3,3), 0 ) copy=processed_img vertices = np.array([[30, 240], [30, 100], [195, 100], [195, 240]]) processed_img = roi(processed_img, np.int32([vertices])) verticesP = np.array([[30, 270], [30, 230], [197, 230], [197, 270]]) platform = roi(copy, np.int32([verticesP])) # edges #lines = cv2.HoughLinesP(platform, 1, np.pi/180, 180,np.array([]), 3, 2) #draw_lines(processed_img,lines) #draw_lines(original_image,lines) #Platform lines #imgray = cv2.cvtColor(platform,cv2.COLOR_BGR2GRAY) ret,thresh = cv2.threshold(platform,127,255,0) im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) cv2.drawContours(original_image, contours, -1, (0,255,0), 3) try: platformpos=contours[0][0][0] except: platformpos=[[0]] circles = cv2.HoughCircles(processed_img, cv2.HOUGH_GRADIENT, 1, 20, param1=90, param2=5, minRadius=1, maxRadius=3) ballpos=draw_circles(original_image,circles=circles) return processed_img,original_image,platform,platformpos,ballpos
def cropCircle(img, resize=None): if resize: if (img.shape[0] > img.shape[1]): tile_size = (int(img.shape[1] * resize / img.shape[0]), resize) else: tile_size = (resize, int(img.shape[0] * resize / img.shape[1])) img = cv2.resize(img, dsize=tile_size, interpolation=cv2.INTER_CUBIC) else: tile_size = img.shape gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY); _, thresh = cv2.threshold(gray, 10, 255, cv2.THRESH_BINARY) _, contours, _ = cv2.findContours(thresh.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) main_contour = sorted(contours, key=cv2.contourArea, reverse=True)[0] ff = np.zeros((gray.shape[0], gray.shape[1]), 'uint8') cv2.drawContours(ff, main_contour, -1, 1, 15) ff_mask = np.zeros((gray.shape[0] + 2, gray.shape[1] + 2), 'uint8') cv2.floodFill(ff, ff_mask, (int(gray.shape[1] / 2), int(gray.shape[0] / 2)), 1) rect = maxRect(ff) rectangle = [min(rect[0], rect[2]), max(rect[0], rect[2]), min(rect[1], rect[3]), max(rect[1], rect[3])] img_crop = img[rectangle[0]:rectangle[1], rectangle[2]:rectangle[3]] cv2.rectangle(ff, (min(rect[1], rect[3]), min(rect[0], rect[2])), (max(rect[1], rect[3]), max(rect[0], rect[2])), 3, 2) return [img_crop, rectangle, tile_size]
def draw_contours(self): """""" # contours all the objects found # (findContours changes the source image, # hence copy) contours, _ = cv2.findContours(self.mask.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # rectangles for contour in contours: size = cv2.contourArea(contour) if size > self.threshold: # only larger objects ret_x, ret_y, ret_w, ret_h = cv2.boundingRect(contour) cv2.rectangle(self.display, (ret_x, ret_y), (ret_x+ret_w, ret_y+ret_h), (0, 255, 255), 2)
def find_components(im, max_components=16): """Dilate the image until there are just a few connected components. Returns contours for these components.""" kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (10, 10)) dilation = dilate(im, kernel, 6) count = 21 n = 0 sigma = 0.000 while count > max_components: n += 1 sigma += 0.005 result = cv2.findContours(dilation, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) if len(result) == 3: _, contours, hierarchy = result elif len(result) == 2: contours, hierarchy = result possible = find_likely_rectangles(contours, sigma) count = len(possible) return (dilation, possible, n)
def extract_rect(im): imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) ret,thresh = cv2.threshold(imgray, 127, 255, 0) contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # finding contour with max area largest = None for cnt in contours: if largest == None or cv2.contourArea(cnt) > cv2.contourArea(largest): largest = cnt peri = cv2.arcLength(largest, True) appr = cv2.approxPolyDP(largest, 0.02 * peri, True) #cv2.drawContours(im, appr, -1, (0,255,0), 3) points_list = [[i[0][0], i[0][1]] for i in appr] left = sorted(points_list, key = lambda p: p[0])[0:2] right = sorted(points_list, key = lambda p: p[0])[2:4] print("l " + str(left)) print("r " + str(right)) lu = sorted(left, key = lambda p: p[1])[0] ld = sorted(left, key = lambda p: p[1])[1] ru = sorted(right, key = lambda p: p[1])[0] rd = sorted(right, key = lambda p: p[1])[1] print("lu " + str(lu)) print("ld " + str(ld)) print("ru " + str(ru)) print("rd " + str(rd)) lu_ = [ (lu[0] + ld[0])/2, (lu[1] + ru[1])/2 ] ld_ = [ (lu[0] + ld[0])/2, (ld[1] + rd[1])/2 ] ru_ = [ (ru[0] + rd[0])/2, (lu[1] + ru[1])/2 ] rd_ = [ (ru[0] + rd[0])/2, (ld[1] + rd[1])/2 ] print("lu_ " + str(lu_)) print("ld_ " + str(ld_)) print("ru_ " + str(ru_)) print("rd_ " + str(rd_)) src_pts = np.float32(np.array([lu, ru, rd, ld])) dst_pts = np.float32(np.array([lu_, ru_, rd_, ld_])) h,w,b = im.shape H, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0) print("H" + str(H)) imw = cv2.warpPerspective(im, H, (w, h)) return imw[lu_[1]:rd_[1], lu_[0]:rd_[0]] # cropping image
def find_components(edges, max_components=16): """Dilate the image until there are just a few connected components. Returns contours for these components.""" # Perform increasingly aggressive dilation until there are just a few # connected components. count = 21 dilation = 5 n = 1 while count > 16: n += 1 dilated_image = dilate(edges, N=3, iterations=n) _, contours, hierarchy = cv2.findContours(dilated_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) count = len(contours) #print dilation #Image.fromarray(edges).show() #Image.fromarray(255 * dilated_image).show() return contours
def camera_gesture_trigger(): # Capture frame-by-frame ret, frame = cap.read() # Our operations on the frame come here gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray,(5,5),0) ret,thresh1 = cv2.threshold(blur,70,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU) contours, hierarchy = cv2.findContours(thresh1,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) max_area=0 for i in range(len(contours)): cnt=contours[i] area = cv2.contourArea(cnt) if(area>max_area): max_area=area ci=i cnt=contours[ci] hull = cv2.convexHull(cnt) moments = cv2.moments(cnt) cnt = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True) hull = cv2.convexHull(cnt,returnPoints = False) defects = cv2.convexityDefects(cnt,hull) if defects is not None: if defects.shape[0] >= 5: return 1 return 0
def classify(img): cimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img2 = cv2.medianBlur(cimg, 13) ret, thresh1 = cv2.threshold(cimg, 100, 120, cv2.THRESH_BINARY) t2 = copy.copy(thresh1) x, y = thresh1.shape arr = np.zeros((x, y, 3), np.uint8) final_contours = [] image, contours, hierarchy = cv2.findContours(t2, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) #cv2.imshow('image', image) #k = cv2.waitKey(0) for i in range(len(contours)): cnt = contours[i] if cv2.contourArea(cnt) > 35000 and cv2.contourArea(cnt) < 15000: cv2.drawContours(img, [cnt], -1, [0, 255, 255]) cv2.fillConvexPoly(arr, cnt, [255, 255, 255]) final_contours.append(cnt) cv2.imshow('arr', arr) k = cv2.waitKey(0) return arr
def get_image_xy_corner(self): """get ?artesian coordinates from raster""" import cv2 if not self.image_path: return False image_xy_corners = [] img = cv2.imread(self.image_path, cv2.IMREAD_GRAYSCALE) imagem = (255 - img) try: ret, thresh = cv2.threshold(imagem, 10, 128, cv2.THRESH_BINARY) try: contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) except Exception: im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) hierarchy = hierarchy[0] hierarhy_contours = [[] for _ in range(len(hierarchy))] for fry in range(len(contours)): currentContour = contours[fry] currentHierarchy = hierarchy[fry] cc = [] # epsilon = 0.0005 * cv2.arcLength(contours[len(contours) - 1], True) approx = cv2.approxPolyDP(currentContour, self.epsilon, True) if len(approx) > 2: for c in approx: cc.append([c[0][0], c[0][1]]) parent_index = currentHierarchy[3] index = fry if parent_index < 0 else parent_index hierarhy_contours[index].append(cc) image_xy_corners = [c for c in hierarhy_contours if len(c) > 0] return image_xy_corners except Exception as ex: self.error(ex) return image_xy_corners
def _detect_bot(self, hsv_image): BOT_MIN = np.array([28,8,100], np.uint8) BOT_MAX = np.array([32,255,255], np.uint8) thresholded_image = cv2.inRange(hsv_image, BOT_MIN, BOT_MAX) thresholded_image = cv2.medianBlur(thresholded_image, 15) _, contours, hierarchy = cv2.findContours(thresholded_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) if not contours: (bot_x, bot_y) = (-1000,-1000) else: bot = contours[0] M = cv2.moments(bot) if len(bot) > 2: bot_x = int(M['m10']/M['m00']) bot_y = int(M['m01']/M['m00']) else: (bot_x, bot_y) = (-1000,-1000) return thresholded_image, (bot_x, bot_y)
def contourImg(image): #Find contours in the image the first and last returns dont matter so the _ is just a placeholder to ignore them _, contours, _ = cv2.findContours(image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) #The contouring operation does some weird stuff to the image so this line just fills the whole thing with black image.fill(0) boundingRect = [] #Loops through all contours bigger than minArea pixels. That number is tweakable and determined by testing for j in [i for i in contours if cv2.contourArea(i) > minArea]: #br is a (list/tuple)? of the form x, y, width, height where (x,y) is the (top/bottom)? (left/right)? corner br = cv2.boundingRect(j) if(abs(br[2]/br[3] - INDASPECT) < indAspectTol and cv2.contourArea(j)/(br[2]*br[3]) > covTol): boundingRect.append(br) for x in range(0, len(boundingRect)): for y in range(x+1, len(boundingRect)): i = boundingRect[x] j = boundingRect[y] if(abs(i[1]-j[1]) < i[3]/2) and abs(abs(i[0]-j[0])/i[1] - GRPASPECT) < grpAspectTol: return [createRectCnt(i), createRectCnt(j)] return None
def diagContour(image): #Find contours in the image the first and last returns dont matter so the _ is just a placeholder to ignore them _, contours, _ = cv2.findContours(image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) #The contouring operation does some weird stuff to the image so this line just fills the whole thing with black image.fill(0) boundingRect = [] firstFail = [] #Loops through all contours bigger than minArea pixels. That number is tweakable and determined by testing for j in [i for i in contours if cv2.contourArea(i) > minArea]: #br is a (list/tuple)? of the form x, y, width, height where (x,y) is the (top/bottom)? (left/right)? corner br = cv2.boundingRect(j) if(abs(br[2]/br[3] - INDASPECT) < indAspectTol and cv2.contourArea(j)/(br[2]*br[3]) > covTol): boundingRect.append(br) else: firstFail.append([br, br[2]/br[3], cv2.contourArea(j)/(br[2]*br[3])]) secondRound = [] for x in range(0, len(boundingRect)): for y in range(x+1, len(boundingRect)): i = boundingRect[x] j = boundingRect[y] secondRound.append([(x,y,i,j), (abs(i[1]-j[1]), i[3]/2), abs(i[0]-j[0])/i[1]]) for x in secondRound: if(x[1][0] < x[1][1] and x[2] - GRPASPECT < grpAspectTol): return firstFail, secondRound, [createRectCnt(x[0][2]), createRectCnt(x[0][3])] return firstFail, secondRound, None
def plateDetect(img,img2): '''?????????????????''' im2, contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) for con in contours: x,y,w,h=cv2.boundingRect(con) area=w*h ratio=w/h if ratio>2 and ratio<4 and area>=2000 and area<=25000: logo_y1=max(0,int(y-h*3.0)) logo_y2=y logo_x1=x logo_x2=x+w img_logo=img2.copy() logo=img_logo[logo_y1:logo_y2,logo_x1:logo_x2] cv2.imwrite('./logo1.jpg',logo) cv2.rectangle(img2,(x,y),(x+w,y+h),(255,0,0),2) cv2.rectangle(img2,(logo_x1,logo_y1),(logo_x2,logo_y2),(0,255,0),2) global plate plate=[x,y,w,h] #????????? return logo
def logoDetect(img,imgo): '''???????????????''' imglogo=imgo.copy() img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) img=cv2.resize(img,(2*img.shape[1],2*img.shape[0]),interpolation=cv2.INTER_CUBIC) #img=cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,-3) ret,img = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) #img=cv2.Sobel(img, cv2.CV_8U, 1, 0, ksize = 9) img=cv2.Canny(img,100,200) element1 = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) element2 = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)) img = cv2.dilate(img, element2,iterations = 1) img = cv2.erode(img, element1, iterations = 3) img = cv2.dilate(img, element2,iterations = 3) #???? im2, contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) tema=0 result=[] for con in contours: x,y,w,h=cv2.boundingRect(con) area=w*h ratio=max(w/h,h/w) if area>300 and area<20000 and ratio<2: if area>tema: tema=area result=[x,y,w,h] ratio2=ratio #?????????????????,?????????? logo2_X=[int(result[0]/2+plate[0]-3),int(result[0]/2+plate[0]+result[2]/2+3)] logo2_Y=[int(result[1]/2+max(0,plate[1]-plate[3]*3.0)-3),int(result[1]/2+max(0,plate[1]-plate[3]*3.0)+result[3]/2)+3] cv2.rectangle(img,(result[0],result[1]),(result[0]+result[2],result[1]+result[3]),(255,0,0),2) cv2.rectangle(imgo,(logo2_X[0],logo2_Y[0]),(logo2_X[1],logo2_Y[1]),(0,0,255),2) print tema,ratio2,result logo2=imglogo[logo2_Y[0]:logo2_Y[1],logo2_X[0]:logo2_X[1]] cv2.imwrite('./logo2.jpg',logo2) return img
def find_components(edges, max_components=16): """Dilate the image until there are just a few connected components. Returns contours for these components.""" # Perform increasingly aggressive dilation until there are just a few # connected components. count = 21 dilation = 5 n = 1 while count > 16: n += 1 dilated_image = dilate(edges, N=3, iterations=n) contours, hierarchy = cv2.findContours(dilated_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) count = len(contours) #print dilation #Image.fromarray(edges).show() #Image.fromarray(255 * dilated_image).show() return contours
def findContours(arg_img,arg_canvas, arg_MinMaxArea=False, arg_debug= False): image= arg_img.copy() #print image canvas= arg_canvas.copy() if len(image)==3: image = cv2.cvtColor(self.image, cv2.COLOR_GRAY2BGR) if sys.version_info.major == 2: ctrs, hier = cv2.findContours(image.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) else: _, ctrs, hier = cv2.findContours(image.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) if arg_MinMaxArea is not False: ctrs = filter(lambda x : arg_MinMaxArea[1]> cv2.contourArea(x) > arg_MinMaxArea[0] , ctrs) print '>>> ', len(ctrs) for ctr in ctrs: print 'Area: ', cv2.contourArea(ctr) cv2.drawContours(canvas, [ctr], 0, (0, 128, 255), 3) if arg_debug: cv2.imwrite('Debug/debug_findContours.jpg',canvas) return canvas
def get_contour(self, arg_frame, arg_export_index, arg_export_path, arg_export_filename, arg_binaryMethod): # Otsu's thresholding after Gaussian filtering tmp = cv2.cvtColor(arg_frame, cv2.COLOR_RGB2GRAY) blur = cv2.GaussianBlur(tmp,(5,5),0) if arg_binaryMethod== 0: ret, thresholdedImg= cv2.threshold(blur.copy() , self.threshold_graylevel, 255 , 0) elif arg_binaryMethod == 1: ret,thresholdedImg = cv2.threshold(blur.copy(),0 ,255 ,cv2.THRESH_BINARY+cv2.THRESH_OTSU) elif arg_binaryMethod== 2: thresholdedImg = cv2.adaptiveThreshold(blur.copy(),255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,5,0) result = cv2.cvtColor(thresholdedImg, cv2.COLOR_GRAY2RGB) ctrs, hier = cv2.findContours(thresholdedImg, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) ctrs = filter(lambda x : cv2.contourArea(x) > self.threshold_size , ctrs) rects = [[cv2.boundingRect(ctr) , ctr] for ctr in ctrs] for rect , cntr in rects: cv2.drawContours(result, [cntr], 0, (0, 128, 255), 3) if arg_export_index: cv2.imwrite(arg_export_path+ arg_export_filename+'.jpg', result) print "Get Contour success" return result
def do(self, bin_img): tmp_bin_img = np.copy(bin_img) if cv2.__version__[0] == "2": contours, hierarchy = cv2.findContours( tmp_bin_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) else: _, contours, hierarchy = cv2.findContours( tmp_bin_img, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) filtered_contours = [] for cnt in contours: x, y, w, h = cv2.boundingRect(cnt) if w * h > self.max_area or w * h < self.min_area: bin_img[y:y+h, x:x+w] = 0 contours = filtered_contours
def get_bounding_rect( cap, win_cap, win, upper, lower): msk = cv2.dilate(cv2.erode( cv2.inRange( cv2.blur( cv2.cvtColor( cap, cv2.COLOR_BGR2HSV ), (5,5) ), np.array(lower), np.array(upper) ), None, iterations=3), None, iterations=3) im2, contours, hierarchy = cv2.findContours( msk, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE ) if len(contours) > 0: areas = [cv2.contourArea(c) for c in contours] # get the area of each contour max_index = np.argmax(areas) # get the index of the largest contour by area cnts = contours[max_index] # get the largest contout by area cv2.drawContours(msk, [cnts], 0, (0,255,0), 3) # Draw the contours to the mask image x,y,w,h = cv2.boundingRect(cnts) # get the bouding box information about the contour cv2.rectangle(win_cap,(x,y),(x+w,y+h),(255,255,255),2) # Draw rectangle on the image to represent the bounding box cv2.imshow( "debug.", win_cap ) try: self.smt_dash.putNumber('vis_x', x) self.smt_dash.putNumber('vis_y', y) self.smt_dash.putNumber('vis_w', w) self.smt_dash.putNumber('vis_h', h) except Exception: pass
def draw_contours(frame): """ Draws a contour around white color. """ print("Drawing contour around white color...") # 'contours' is a list of contours found. contours, _ = cv2.findContours( frame, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # Finding the contour with the greatest area. largest_contour_index = find_largest_contour_index(contours) # Draw the largest contour in the image. cv2.drawContours(frame, contours, largest_contour_index, (255, 255, 255), thickness=-1) # Draw a rectangle around the contour perimeter contour_dimensions = cv2.boundingRect(contours[largest_contour_index]) # cv2.rectangle(sign_image,(x,y),(x+w,y+h),(255,255,255),0,8) print("Done!") return (frame, contour_dimensions)
def cropCircle(img): ''' there many imaged taken thresholded, which means many images is present as a circle with black surrounded. This function is to find the largest inscribed rectangle to the thresholed image and then crop the image to the rectangle. input: img - the cv2 module return: img_crop, rectangle, tile_size ''' if(img.shape[0] > img.shape[1]): tile_size = (int(img.shape[1]*256/img.shape[0]),256) else: tile_size = (256, int(img.shape[0]*256/img.shape[1])) img = cv2.resize(img, dsize=tile_size) gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY); _, thresh = cv2.threshold(gray, 10, 255, cv2.THRESH_BINARY) _, contours, _ = cv2.findContours(thresh.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE) main_contour = sorted(contours, key = cv2.contourArea, reverse = True)[0] ff = np.zeros((gray.shape[0],gray.shape[1]), 'uint8') cv2.drawContours(ff, main_contour, -1, 1, 15) ff_mask = np.zeros((gray.shape[0]+2,gray.shape[1]+2), 'uint8') cv2.floodFill(ff, ff_mask, (int(gray.shape[1]/2), int(gray.shape[0]/2)), 1) rect = maxRect(ff) rectangle = [min(rect[0],rect[2]), max(rect[0],rect[2]), min(rect[1],rect[3]), max(rect[1],rect[3])] img_crop = img[rectangle[0]:rectangle[1], rectangle[2]:rectangle[3]] cv2.rectangle(ff,(min(rect[1],rect[3]),min(rect[0],rect[2])),(max(rect[1],rect[3]),max(rect[0],rect[2])),3,2) return [img_crop, rectangle, tile_size]
def extract_black_contours(img): """ Extract contours for black objects on a white background. Args: img (np.ndarray): the (black and white?) image Returns: list[np.ndarray]: the contours """ img_inverted = 255 - img _, contours, _ = cv2.findContours(img_inverted, mode=cv2.RETR_TREE, method=cv2.CHAIN_APPROX_SIMPLE) return contours # TODO: A ContourGroups class would make this cleaner
def find_display_contour(edge_img_arr): display_contour = None edge_copy = edge_img_arr.copy() contours,hierarchy = cv2.findContours(edge_copy, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) top_cntrs = sorted(contours, key = cv2.contourArea, reverse = True)[:10] for cntr in top_cntrs: peri = cv2.arcLength(cntr,True) approx = cv2.approxPolyDP(cntr, 0.02 * peri, True) if len(approx) == 4: display_contour = approx break return display_contour
def FindField(self): #Feld: Hue zwischen 60 und 100 LowerGreen = np.array([40,0,0]) UpperGreen = np.array([90,255,150]) mask = cv2.inRange(self.ImgHSV,LowerGreen,UpperGreen) # plt.figure() # plt.imshow(mask,cmap='gray') mask = self.SmoothFieldMask(mask) # plt.figure() # plt.imshow(mask.copy(),cmap='gray') im2, contours, hierarchy = cv2.findContours(mask.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) if(len(contours) <= 0): return contours_sorted = sorted(contours, key = cv2.contourArea, reverse=True)[:10] peri = cv2.arcLength(contours_sorted[0],True) approx = cv2.approxPolyDP(contours_sorted[0], 0.02*peri, True) if(len(approx) >-1):#== 4): self.FieldContours = approx cv2.rectangle(mask,(((self.FieldContours[0])[0])[0],((self.FieldContours[0])[0])[1]),(((self.FieldContours[2])[0])[0],((self.FieldContours[2])[0])[1]),(128,128,128),3) # plt.imshow(mask, cmap="gray") # plt.show()
def create_bounding_box(img_path, outfile_name, random_noise = True): img = cv2.imread(img_path) img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret, binary_img = cv2.threshold(img_gray,127,255,cv2.THRESH_BINARY) # show the binary_image # plt.subplot(1,1,1), plt.imshow(binary_img,'gray') # plt.show() image_cnt, contours, _ = cv2.findContours(binary_img,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) x,y,w,h = cv2.boundingRect(contours[0]) if (random_noise == True): w_org = w h_org = h x = int(np.random.normal(x, w_org * 0.15, 1)) y = int(np.random.normal(y, h_org * 0.15, 1)) w = int(np.random.normal(w, w_org * 0.15, 1)) h = int(np.random.normal(h, h_org * 0.15, 1)) height, width, channels = img.shape out_img = np.zeros((height,width,1), np.uint8) cv2.rectangle(out_img,(x,y),(x+w,y+h),(255,0,0),-1) cv2.imwrite(outfile_name, out_img)
def movement(mat_1,mat_2): mat_1_gray = cv2.cvtColor(mat_1.copy(),cv2.COLOR_BGR2GRAY) mat_1_gray = cv2.blur(mat_1_gray,(blur1,blur1)) _,mat_1_gray = cv2.threshold(mat_1_gray,100,255,0) mat_2_gray = cv2.cvtColor(mat_2.copy(),cv2.COLOR_BGR2GRAY) mat_2_gray = cv2.blur(mat_2_gray,(blur1,blur1)) _,mat_2_gray = cv2.threshold(mat_2_gray,100,255,0) mat_2_gray = cv2.bitwise_xor(mat_1_gray,mat_2_gray) mat_2_gray = cv2.blur(mat_2_gray,(blur2,blur2)) _,mat_2_gray = cv2.threshold(mat_2_gray,70,255,0) mat_2_gray = cv2.erode(mat_2_gray,np.ones((erodeval,erodeval))) mat_2_gray = cv2.dilate(mat_2_gray,np.ones((4,4))) _, contours,__ = cv2.findContours(mat_2_gray,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) if len(contours) > 0:return True #If there were any movements return False #if not #Pedestrian Recognition Thread
def Q2(): cap = cv2.VideoCapture(0) while(cap.isOpened() ): ret = cap.set(3,320) ret = cap.set(4,240) ret, frame = cap.read() if ret==True: gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) x,thresh = cv2.threshold(gray,137,255,1) contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) cv2.drawContours(frame, contours,-1, (0,255,0), 3) cv2.imshow('Image with contours',frame) if cv2.waitKey(1) & 0xFF == ord('q'): break else: break cap.release() cv2.destroyAllWindows()
def sizeFiltering(contours): #this function filters out the smaller retroreflector (as well as any noise) by size #_, contours, _ = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) """blank_image = np.zeros((img.shape[0],img.shape[1],3), np.uint8) cv2.drawContours(blank_image, contours, -1, (255, 255, 255)) cv2.imshow("imagia", blank_image) cv2.waitKey()""" if len(contours) == 0: print "errorrrrr" return 0 big = contours[0] for c in contours: if type(c) and type(big) == np.ndarray: if cv2.contourArea(c) > cv2.contourArea(big): big = c else: print type(c) and type(big) return 0 """blank_image = np.zeros((img.shape[0],img.shape[1],3), np.uint8) cv2.drawContours(blank_image, big, -1, (255, 255, 255)) cv2.imshow("imagia", blank_image) cv2.waitKey()""" """blank_image = np.zeros((img.shape[0],img.shape[1],3), np.uint8) cv2.drawContours(blank_image, big, -1, (255, 255, 255))""" x,y,w,h = cv2.boundingRect(big) """cv2.rectangle(blank_image, (x,y), (x+w, y+h), (255,255,255)) cv2.imshow("rect", blank_image) cv2.waitKey()""" return big
def shapeFiltering(img): contours = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[0] if len(contours) == 0: return "yoopsie" #else: #print contours """blank_image = np.zeros((img.shape[0],img.shape[1],3), np.uint8) cv2.drawContours(blank_image, contours, -1, (255, 255, 255)) cv2.imshow("imagiae", blank_image) cv2.waitKey()""" good_shape = [] for c in contours: x,y,w,h = cv2.boundingRect(c) """rect = cv2.minAreaRect(contour) box = cv2.boxPoints(rect) box = np.int0(box) w = """ #if h == 0: # continue ratio = w / h ratio_grade = ratio / (TMw / TMh) if 0.2 < ratio_grade < 1.8: good_shape.append(c) """blank_image = np.zeros((img.shape[0],img.shape[1],3), np.uint8) cv2.drawContours(blank_image, good_shape, -1, (255, 255, 255)) cv2.imshow("imagia", blank_image) cv2.waitKey()""" return good_shape
def track(self, com, size=(250, 250, 250), dsize=(128, 128), doHandSize=True): """ Detect the hand as closest object to camera :param size: bounding box size :return: center of mass of hand """ # calculate boundaries xstart, xend, ystart, yend, zstart, zend = self.comToBounds(com, size) # crop patch from source cropped = self.getCrop(self.dpt, xstart, xend, ystart, yend, zstart, zend) # predict movement of CoM if self.refineNet is not None and self.importer is not None: rz = self.resizeCrop(cropped, dsize) newCom3D = self.refineCoM(rz, size, com) + self.importer.jointImgTo3D(com) com = self.importer.joint3DToImg(newCom3D) if numpy.allclose(com, 0.): com[2] = cropped[cropped.shape[0]//2, cropped.shape[1]//2] else: raise RuntimeError("Need refineNet for this") if doHandSize is True: # refined contour for size estimation zstart = com[2] - size[2] / 2. zend = com[2] + size[2] / 2. part_ref = self.dpt.copy() part_ref[part_ref < zstart] = 0 part_ref[part_ref > zend] = 0 part_ref[part_ref != 0] = 10 # set to something ret, thresh_ref = cv2.threshold(part_ref, 1, 255, cv2.THRESH_BINARY) contours_ref, _ = cv2.findContours(thresh_ref.astype(dtype=numpy.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # find the largest contour areas = [cv2.contourArea(cc) for cc in contours_ref] c_max = numpy.argmax(areas) # final result return com, self.estimateHandsize(contours_ref[c_max], com, size) else: return com, size
def find_concetric_circles(gray_img,min_ring_count=3, visual_debug=False): # get threshold image used to get crisp-clean edges using blur to remove small features edges = cv2.adaptiveThreshold(cv2.blur(gray_img,(3,3)), 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 5, 11) _, contours, hierarchy = cv2.findContours(edges, mode=cv2.RETR_TREE, method=cv2.CHAIN_APPROX_NONE,offset=(0,0)) #TC89_KCOS if visual_debug is not False: cv2.drawContours(visual_debug,contours,-1,(200,0,0)) if contours is None or hierarchy is None: return [] clusters = get_nested_clusters(contours,hierarchy[0],min_nested_count=min_ring_count) concentric_cirlce_clusters = [] #speed up code by caching computed ellipses ellipses = {} # for each cluster fit ellipses and cull members that dont have good ellipse fit for cluster in clusters: if visual_debug is not False: cv2.drawContours(visual_debug, [contours[i] for i in cluster],-1, (0,0,255)) candidate_ellipses = [] for i in cluster: c = contours[i] if len(c)>5: if not i in ellipses: e = cv2.fitEllipse(c) fit = max(dist_pts_ellipse(e,c)) ellipses[i] = e,fit else: e,fit = ellipses[i] a,b = e[1][0]/2.,e[1][1]/2. if fit<max(2,max(e[1])/20): candidate_ellipses.append(e) if visual_debug is not False: cv2.ellipse(visual_debug, e, (0,255,0),1) if candidate_ellipses: cluster_center = np.mean(np.array([e[0] for e in candidate_ellipses]),axis=0) candidate_ellipses = [e for e in candidate_ellipses if np.linalg.norm(e[0]-cluster_center)<max(3,min(e[1])/20) ] if len(candidate_ellipses) >= min_ring_count: concentric_cirlce_clusters.append(candidate_ellipses) if visual_debug is not False: cv2.ellipse(visual_debug, candidate_ellipses[-1], (0,255,255),4) #return clusters sorted by size of outmost cirlce biggest first. return sorted(concentric_cirlce_clusters,key=lambda e:-max(e[-1][1]))
def single_finger_check(self, cnt): # use single finger image to check current fame has single finger grey_fin1 = cv2.cvtColor(self.fin1, cv2.COLOR_BGR2GRAY) _, thresh_fin1 = cv2.threshold(grey_fin1, 127, 255, 0) contour_fin1, hierarchy = cv2.findContours(thresh_fin1.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) cnt1 = contour_fin1[0] ret1 = cv2.matchShapes(cnt, cnt1, 1, 0) grey_fin2 = cv2.cvtColor(self.fin2, cv2.COLOR_BGR2GRAY) _, thresh_fin2 = cv2.threshold(grey_fin2, 127, 255, 0) contour_fin2, hierarchy = cv2.findContours(thresh_fin2.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) cnt2 = contour_fin2[0] ret2 = cv2.matchShapes(cnt, cnt2, 1, 0) grey_fin3 = cv2.cvtColor(self.fin3, cv2.COLOR_BGR2GRAY) _, thresh_fin3 = cv2.threshold(grey_fin3, 127, 255, 0) contour_fin3, hierarchy = cv2.findContours(thresh_fin3.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) cnt3 = contour_fin3[0] ret3 = cv2.matchShapes(cnt, cnt3, 1, 0) reta = (ret1 + ret2 + ret3)/3 if reta <= 0.3: return 5 # set as one-finger module else: return 0 # not detect, still 0 # Use PyAutoGUI to control mouse event
def find(self, mode): self.mode = mode if mode == 1: self.modeDesc = 'Run gaussianBlur(), then cannyThresholding' self.gaussianBlur() self.cannyThresholding() elif mode == 2: # Check Gimp Hints self.gimpMarkup() #self.cannyThresholding() self.modeDesc = 'Run gimpMarkup' elif mode == 3: # Massively mask red as a precursor phase self.gaussianBlur() self.colourMapping() self.solidRedFilter() #self.cannyThresholding() self.modeDesc = 'Run gaussianBlur(), colourMapping(), solidRedFilter(), #cannyThresholding' elif mode == 4: self.modeDesc = 'Run gaussianBlur(), then cannyThresholding with RETR_EXTERNAL contour removal mode' self.gaussianBlur() self.cannyThresholding(cv2.RETR_EXTERNAL) elif mode == 5: self.modeDesc = 'Run gaussianBlur(), then cannyThresholding with RETR_TREE contour removal mode' self.gaussianBlur() self.cannyThresholding(cv2.RETR_TREE) # Apply Heuristics to filter out false self.squares = filterContoursRemove(self.img, self.squares) return self.squares
def binaryContoursNestingFilterHeuristic(img, cnts, *args, **kwargs): ''' Concept : Use the found contours, with binary drawn contours to extract hierarchy and hence filter on nesting. Critique : WIP ''' # Set the image to black (0): img[:,:] = (0,0,0) # Draw all of the contours on the image in white contours = [c.contour for c in cnts] cv2.drawContours( img, contours, -1, (255, 255, 255), 1 ) iv = ImageViewer(img) iv.windowShow() # Now extract any channel gray = cv2.split(img)[0] iv = ImageViewer(gray) iv.windowShow() retval, bin = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY) iv = ImageViewer(bin) iv.windowShow() # Now find the contours again, but this time we care about hierarchy (hence _TREE) - we get back next, previous, first_child, parent bin, contours, hierarchy = cv2.findContours(bin, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) iv = ImageViewer(bin) iv.windowShow() # Alternative flags : only take the external contours bin, contours, hierarchy = cv2.findContours(bin, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) iv = ImageViewer(bin) iv.windowShow() return cnts
def usage(): print(''' piwall.py --vssdemo|-v rotating : iterate the VideoSquareSearch over rotating video, and output located data in piwall-search-mono.avi --vssdemo|-v album : iterate the VideoSquareSearch over sequence of images, and output located data in album.avi --sfv3mode|-s [mode 1-3] : run the SquareLocatorV3 algorithm : set the mode 1-3 < default image 2x2-red-1.jpg > : 1 => call gaussianBlur(); cannyThresholding() : 2 => call gimpMarkup() : 3 => call gaussianBlur(); colourMapping(); solidRedFilter(); [#cannyThresholding] : 4 => as 1, but with cv2.RETR_EXTERNAL as contour_retrieval_mode : 5 => as 1, but with cv2.RETR_TREE as contour_retrieval_mode, then filter only outermost contours : 6 => new model which takes a series of images which have transitions that identify the monitors. --sfv3img|-i [image path]: run the SquareFinderV3 algorithm : set the input image < default mode 1> --sfv4glob|-g [image glob pattern] : set the series of input images to be pattern-[%03d].jpg ''')
def find_contours(image): #return cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE); #return cv2.findContours(image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE); return cv2.findContours(image, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE);
def find_bbox(mask_binary, margin_factor=None): ret, thresh = cv2.threshold(mask_binary, 127, 255, 0) _, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # Find the index of the largest contour areas = [cv2.contourArea(c) for c in contours] if len(areas) == 0: return (0, 0, mask_binary.shape[0], mask_binary.shape[1], False) else: max_index = np.argmax(areas) cnt = contours[max_index] x, y, w, h = cv2.boundingRect(cnt) if margin_factor != None and margin_factor > 0: wm = w * margin_factor hm = h * margin_factor x -= wm y -= hm w += 2 * wm h += 2 * hm x = max(0, x) y = max(0, y) X = min(x + w, mask_binary.shape[1]) Y = min(y + h, mask_binary.shape[0]) w = X - x h = Y - y return (int(x), int(y), int(w), int(h), True)
def get_operator(path, url=False, expand=False): if url: req = requests.get(path) arr = np.asarray(bytearray(req.content), dtype=np.uint8) shape = cv2.resize(cv2.imdecode(arr, -1), (69, 69)) else: shape = cv2.resize(cv2.imread('shape.png'), (69, 69)) shape_gray = cv2.cvtColor(shape, cv2.COLOR_BGR2GRAY) _, shape_binary = cv2.threshold(shape_gray, 127, 255, cv2.THRESH_BINARY) _, contours, hierarchy = cv2.findContours(shape_binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) contour = contours[0] operator = np.zeros((69, 69)) for point in contour: operator[point[0][0]][point[0][1]] = 1 if expand: if point[0][0] > 0: operator[point[0][0] - 1][point[0][1]] = 1 if point[0][0] < 68: operator[point[0][0] + 1][point[0][1]] = 1 if point[0][1] > 0: operator[point[0][0]][point[0][1] - 1] = 1 if point[0][1] < 68: operator[point[0][0]][point[0][1] + 1] = 1 return operator