我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用cv2.boundingRect()。
def __bound_contours(roi): """ returns modified roi(non-destructive) and rectangles that founded by the algorithm. @roi region of interest to find contours @return (roi, rects) """ roi_copy = roi.copy() roi_hsv = cv2.cvtColor(roi, cv2.COLOR_RGB2HSV) # filter black color mask1 = cv2.inRange(roi_hsv, np.array([0, 0, 0]), np.array([180, 255, 125])) mask1 = cv2.morphologyEx(mask1, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))) mask1 = cv2.Canny(mask1, 100, 300) mask1 = cv2.GaussianBlur(mask1, (1, 1), 0) mask1 = cv2.Canny(mask1, 100, 300) # mask1 = cv2.morphologyEx(mask1, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))) # Find contours for detected portion of the image im2, cnts, hierarchy = cv2.findContours(mask1.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5] # get largest five contour area rects = [] for c in cnts: peri = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, 0.02 * peri, True) x, y, w, h = cv2.boundingRect(approx) if h >= 15: # if height is enough # create rectangle for bounding rect = (x, y, w, h) rects.append(rect) cv2.rectangle(roi_copy, (x, y), (x+w, y+h), (0, 255, 0), 1); return (roi_copy, rects)
def crop_and_store(frame, mouth_coordinates, name): """ Args: 1. frame: The frame which has to be cropped. 2. mouth_coordinates: The coordinates which help in deciding which region is to be cropped. 3. name: The path name to be used for storing the cropped image. """ # Find bounding rectangle for mouth coordinates x, y, w, h = cv2.boundingRect(mouth_coordinates) mouth_roi = frame[y:y + h, x:x + w] h, w, channels = mouth_roi.shape # If the cropped region is very small, ignore this case. if h < 10 or w < 10: return resized = resize(mouth_roi, 32, 32) cv2.imwrite(name, resized)
def extract_corners(self, image): """ Find the 4 corners of a binary image :param image: binary image :return: 4 main vertices or None """ cnts, _ = cv2.findContours(image.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2:] cnt = cnts[0] _, _, h, w = cv2.boundingRect(cnt) epsilon = min(h, w) * 0.5 vertices = cv2.approxPolyDP(cnt, epsilon, True) vertices = cv2.convexHull(vertices, clockwise=True) vertices = self.correct_vertices(vertices) return vertices
def find_squares(img): img = cv2.GaussianBlur(img, (5, 5), 0) squares = [] for gray in cv2.split(img): for thrs in xrange(0, 255, 26): if thrs == 0: bin = cv2.Canny(gray, 0, 50, apertureSize=5) bin = cv2.dilate(bin, None) else: _retval, bin = cv2.threshold(gray, thrs, 255, cv2.THRESH_BINARY) contours, _hierarchy = find_contours(bin, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) for cnt in contours: x, y, w, h = cv2.boundingRect(cnt) cnt_len = cv2.arcLength(cnt, True) cnt = cv2.approxPolyDP(cnt, 0.02*cnt_len, True) area = cv2.contourArea(cnt) if len(cnt) == 4 and 20 < area < 1000 and cv2.isContourConvex(cnt): cnt = cnt.reshape(-1, 2) max_cos = np.max([angle_cos( cnt[i], cnt[(i+1) % 4], cnt[(i+2) % 4] ) for i in xrange(4)]) if max_cos < 0.1: if (1 - (float(w) / float(h)) <= 0.07 and 1 - (float(h) / float(w)) <= 0.07): squares.append(cnt) return squares
def affine_skew(self, tilt, phi, img, mask=None): h, w = img.shape[:2] if mask is None: mask = np.zeros((h, w), np.uint8) mask[:] = 255 A = np.float32([[1, 0, 0], [0, 1, 0]]) if phi != 0.0: phi = np.deg2rad(phi) s, c = np.sin(phi), np.cos(phi) A = np.float32([[c, -s], [s, c]]) corners = [[0, 0], [w, 0], [w, h], [0, h]] tcorners = np.int32(np.dot(corners, A.T)) x, y, w, h = cv2.boundingRect(tcorners.reshape(1, -1, 2)) A = np.hstack([A, [[-x], [-y]]]) img = cv2.warpAffine(img, A, (w, h), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE) if tilt != 1.0: s = 0.8*np.sqrt(tilt * tilt - 1) img = cv2.GaussianBlur(img, (0, 0), sigmaX=s, sigmaY=0.01) img = cv2.resize(img, (0, 0), fx=1.0 / tilt, fy=1.0, interpolation=cv2.INTER_NEAREST) A[0] /= tilt if phi != 0.0 or tilt != 1.0: h, w = img.shape[:2] mask = cv2.warpAffine(mask, A, (w, h), flags=cv2.INTER_NEAREST) Ai = cv2.invertAffineTransform(A) return img, mask, Ai
def sizeFiltering(contours): """ this function filters out the smaller retroreflector (as well as any noise) by size """ if len(contours) == 0: print "sizeFiltering: Error, no contours found" return 0 big = contours[0] for c in contours: if type(c) and type(big) == numpy.ndarray: if cv2.contourArea(c) > cv2.contourArea(big): big = c else: print type(c) and type(big) return 0 x,y,w,h = cv2.boundingRect(big) return big
def profile_score(contour, binary): """ Calculate a score based on the "profile" of the target, basically how closely its geometry matches with the expected geometry of the goal :param contour: :param binary: :return: """ bounding = cv2.boundingRect(contour) pixels = np.zeros((binary.shape[0], binary.shape[1])) cv2.drawContours(pixels, [contour], -1, 255, -1) col_averages = np.mean(pixels, axis=0)[bounding[0]:bounding[0] + bounding[2]] row_averages = np.mean(pixels, axis=1)[bounding[1]:bounding[1] + bounding[3]] # normalize to between 0 and 1 col_averages *= 1.0 / col_averages.max() row_averages *= 1.0 / row_averages.max() col_diff = np.subtract(col_averages, col_profile(col_averages.shape[0], bounding[2])) row_diff = np.subtract(row_averages, row_profile(row_averages.shape[0], bounding[3])) # average difference should be close to 0 avg_diff = np.mean([np.mean(col_diff), np.mean(row_diff)]) return 100 - (avg_diff * 50)
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 sort_contours(cnts, method="left-to-right"): # initialize the reverse flag and sort index reverse = False i = 0 # handle if we need to sort in reverse if method == "right-to-left" or method == "bottom-to-top": reverse = True # handle if we are sorting against the y-coordinate rather than # the x-coordinate of the bounding box if method == "top-to-bottom" or method == "bottom-to-top": i = 1 # construct the list of bounding boxes and sort them from top to # bottom boundingBoxes = [cv2.boundingRect(c) for c in cnts] (cnts, boundingBoxes) = zip(*sorted(zip(cnts, boundingBoxes), key=lambda b:b[1][i], reverse=reverse)) # return the list of sorted contours and bounding boxes return (cnts, boundingBoxes)
def find_contours(self, img): thresh_img = self.threshold(img) _, contours, _ = cv2.findContours(thresh_img, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) result = [] for cnt in contours: approx = cv2.approxPolyDP(cnt, 0.01*cv2.arcLength(cnt, True), True) if self.draw_approx: cv2.drawContours(self.out, [approx], -1, self.BLUE, 2, lineType=8) if len(approx) > 3 and len(approx) < 15: _, _, w, h = cv2.boundingRect(approx) if h > self.min_height and w > self.min_width: hull = cv2.convexHull(cnt) approx2 = cv2.approxPolyDP(hull,0.01*cv2.arcLength(hull,True),True) if self.draw_approx2: cv2.drawContours(self.out, [approx2], -1, self.GREEN, 2, lineType=8) result.append(approx2) return result
def mark_hand_center(frame_in,cont): max_d=0 pt=(0,0) x,y,w,h = cv2.boundingRect(cont) for ind_y in xrange(int(y+0.3*h),int(y+0.8*h)): #around 0.25 to 0.6 region of height (Faster calculation with ok results) for ind_x in xrange(int(x+0.3*w),int(x+0.6*w)): #around 0.3 to 0.6 region of width (Faster calculation with ok results) dist= cv2.pointPolygonTest(cont,(ind_x,ind_y),True) if(dist>max_d): max_d=dist pt=(ind_x,ind_y) if(max_d>radius_thresh*frame_in.shape[1]): thresh_score=True cv2.circle(frame_in,pt,int(max_d),(255,0,0),2) else: thresh_score=False return frame_in,pt,max_d,thresh_score # 6. Find and display gesture
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 get_contours(image, polydb=0.1, contour_range=7): # find the contours in the edged image, keeping only the largest ones, and initialize the screen contour contours = _findContours(image, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) cnts = sorted(contours, key = cv2.contourArea, reverse = True)[:contour_range] # loop over the contours screenCnt = None for c in cnts: # approximate the contour peri = cv2.arcLength(c, True) #finds the Contour Perimeter approx = cv2.approxPolyDP(c, polydb * peri, True) # if our approximated contour has four points, then we can assume that we have found our screen if len(approx) == 4: screenCnt = approx break if screenCnt is None: raise EdgeNotFound() # sometimes the algorythm finds a strange non-convex shape. The shape conforms to the card but its not complete, so then just complete the shape into a convex form if not cv2.isContourConvex(screenCnt): screenCnt = cv2.convexHull(screenCnt) x,y,w,h = cv2.boundingRect(screenCnt) screenCnt = numpy.array([[[x, y]], [[x+w, y]], [[x+w, y+h]], [[x, y+h]]]) return screenCnt
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 findSquare( self,frame ): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(gray, (7, 7), 0) edged = cv2.Canny(blurred, 60, 60) # find contours in the edge map (cnts, _) = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # loop over our contours to find hexagon cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:50] screenCnt = None for c in cnts: # approximate the contour peri = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, 0.004 * peri, True) # if our approximated contour has four points, then # we can assume that we have found our squeare if len(approx) >= 4: screenCnt = approx x,y,w,h = cv2.boundingRect(c) cv2.drawContours(image, [approx], -1, (0, 0, 255), 1) #cv2.imshow("Screen", image) #create the mask and remove rest of the background mask = np.zeros(image.shape[:2], dtype = "uint8") cv2.drawContours(mask, [screenCnt], -1, 255, -1) masked = cv2.bitwise_and(image, image, mask = mask) #cv2.imshow("Masked",masked ) #crop the masked image to to be compared to referance image cropped = masked[y:y+h,x:x+w] #scale the image so it is fixed size as referance image cropped = cv2.resize(cropped, (200,200), interpolation =cv2.INTER_AREA) return cropped
def extract_corners(self, image): """ Find the 4 corners of a binary image :param image: binary image :return: 4 main vertices or None """ cnts, _ = cv2.findContours(image.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2:] cnt = cnts[0] _, _, h, w = cv2.boundingRect(cnt) epsilon = min(h, w) * 0.5 o_vertices = cv2.approxPolyDP(cnt, epsilon, True) vertices = cv2.convexHull(o_vertices, clockwise=True) vertices = self.correct_vertices(vertices) if self.debug: temp = cv2.cvtColor(image.copy(), cv2.COLOR_GRAY2BGR) cv2.drawContours(temp, cnts, -1, (0, 255, 0), 10) cv2.drawContours(temp, o_vertices, -1, (255, 0, 0), 30) cv2.drawContours(temp, vertices, -1, (0, 0, 255), 20) self.save2image(temp) return vertices
def find_chars(img): gray = np.array(img.convert("L")) ret, mask = cv2.threshold(gray, 180, 255, cv2.THRESH_BINARY) image_final = cv2.bitwise_and(gray, gray, mask=mask) ret, new_img = cv2.threshold(image_final, 180, 255, cv2.THRESH_BINARY_INV) kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3)) dilated = cv2.dilate(new_img, kernel, iterations=1) # Image.fromarray(dilated).save('out.png') # for debugging _, contours, hierarchy = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) coords = [] for contour in contours: # get rectangle bounding contour [x, y, w, h] = cv2.boundingRect(contour) # ignore large chars (probably not chars) if w > 70 and h > 70: continue coords.append((x, y, w, h)) return coords # find list of eye coordinates in image
def keep_box(contour): xx, yy, w_, h_ = cv2.boundingRect(contour) # width and height need to be floats w_ *= 1.0 h_ *= 1.0 # Test it's shape - if it's too oblong or tall it's # probably not a real character if w_ / h_ < 0.1 or w_ / h_ > 10: if DEBUG: print "\t Rejected because of shape: (" + str(xx) + "," + str(yy) + "," + str(w_) + "," + str(h_) + ")" + \ str(w_ / h_) return False # check size of the box if ((w_ * h_) > ((img_x * img_y) / 5)) or ((w_ * h_) < 15): if DEBUG: print "\t Rejected because of size" return False return True
def test_initial_pass_through_compare(self): original = cv2.imread(os.path.join(self.provider.assets, "start_screen.png")) against = self.provider.get_img_from_screen_shot() wrong = cv2.imread(os.path.join(self.provider.assets, "battle.png")) # convert the images to grayscale original = mask_image([127], [255], cv2.cvtColor(original, cv2.COLOR_BGR2GRAY), True) against = mask_image([127], [255], cv2.cvtColor(against, cv2.COLOR_BGR2GRAY), True) wrong = mask_image([127], [255], cv2.cvtColor(wrong, cv2.COLOR_BGR2GRAY), True) # initialize the figure (score, diff) = compare_ssim(original, against, full=True) diff = (diff * 255).astype("uint8") self.assertTrue(score > .90, 'If this is less then .90 the initial compare of the app will fail') (score, nothing) = compare_ssim(original, wrong, full=True) self.assertTrue(score < .90) if self.__debug_pictures__: # threshold the difference image, followed by finding contours to # obtain the regions of the two input images that differ thresh = cv2.threshold(diff, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1] cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[0] # loop over the contours for c in cnts: # compute the bounding box of the contour and then draw the # bounding box on both input images to represent where the two # images differ (x, y, w, h) = cv2.boundingRect(c) cv2.rectangle(original, (x, y), (x + w, y + h), (0, 0, 255), 2) cv2.rectangle(against, (x, y), (x + w, y + h), (0, 0, 255), 2) # show the output images diffs = ("Original", original), ("Modified", against), ("Diff", diff), ("Thresh", thresh) images = ("Original", original), ("Against", against), ("Wrong", wrong) self.setup_compare_images(diffs) self.setup_compare_images(images)
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 remove_border(contour, ary): """Remove everything outside a border contour.""" # Use a rotated rectangle (should be a good approximation of a border). # If it's far from a right angle, it's probably two sides of a border and # we should use the bounding box instead. c_im = np.zeros(ary.shape) r = cv2.minAreaRect(contour) degs = r[2] if angle_from_right(degs) <= 10.0: box = cv2.boxPoints(r) box = np.int0(box) cv2.drawContours(c_im, [box], 0, 255, -1) cv2.drawContours(c_im, [box], 0, 0, 4) else: x1, y1, x2, y2 = cv2.boundingRect(contour) cv2.rectangle(c_im, (x1, y1), (x2, y2), 255, -1) cv2.rectangle(c_im, (x1, y1), (x2, y2), 0, 4) return np.minimum(c_im, ary)
def _find_size_candidates(self, image): binary_image = self._filter_image(image) _, contours, _ = cv2.findContours(binary_image, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) size_candidates = [] for contour in contours: bounding_rect = cv2.boundingRect(contour) contour_area = cv2.contourArea(contour) if self._is_valid_contour(contour_area, bounding_rect): candidate = (bounding_rect[2] + bounding_rect[3]) / 2 size_candidates.append(candidate) return size_candidates
def keepBox(contour): xx, yy, w_, h_ = cv2.boundingRect(contour) # width and height need to be floats w_ *= 1.0 h_ *= 1.0 # Test it's shape - if it's too oblong or tall it's # probably not a real character if w_ / h_ < 0.1 or w_ / h_ > 10: if DEBUG: print "\t Rejected because of shape: (" + str(xx) + "," + str(yy) + "," + str(w_) + "," + str(h_) + ")" + \ str(w_ / h_) return False # check size of the box if ((w_ * h_) > ((img_x * img_y) / 5)) or ((w_ * h_) < 15): if DEBUG: print "\t Rejected because of size" return False return True # whether contour is a child
def findIDcnt(countours): #???????? widths = [] for idx, cnt in enumerate(countours): x, y, width, height = cv2.boundingRect(cnt) widths.insert(idx, width) #??????????? IDList = heapq.nlargest(3, widths) #??????????????????? IDcnts = [] for idx, item in enumerate(IDList): index = widths.index(item) IDcnts.insert(idx, countours[index]) # print IDcnts return IDcnts # ????
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 boundingRects(scale, contours): for contour in contours: epsilon = 0.1 * cv2.arcLength(contour, True) approx = cv2.approxPolyDP(contour, epsilon, True) x, y, w, h = cv2.boundingRect(approx) yield [x * scale, y * scale, w * scale, h * scale]
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 remove_border(contour, ary): """Remove everything outside a border contour.""" # Use a rotated rectangle (should be a good approximation of a border). # If it's far from a right angle, it's probably two sides of a border and # we should use the bounding box instead. c_im = np.zeros(ary.shape) r = cv2.minAreaRect(contour) degs = r[2] if angle_from_right(degs) <= 10.0: box = cv2.cv.BoxPoints(r) box = np.int0(box) cv2.drawContours(c_im, [box], 0, 255, -1) cv2.drawContours(c_im, [box], 0, 0, 4) else: x1, y1, x2, y2 = cv2.boundingRect(contour) cv2.rectangle(c_im, (x1, y1), (x2, y2), 255, -1) cv2.rectangle(c_im, (x1, y1), (x2, y2), 0, 4) return np.minimum(c_im, ary)
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_text_with_location(boxed_image, contours, img): image_text_dict = {} for contour in contours: # get rectangle bounding contour [x, y, w, h] = cv2.boundingRect(contour) # draw rectangle around contour on original image if w < 20 or h < 20: continue cv2.rectangle(boxed_image, (x, y), (x + w + 10, y + h + 10), thickness=2, color=0) box_read = extract_image_from_location(img, x, y, w, h) box_read = box_read.strip() image_text_dict[(x, y)] = box_read return image_text_dict
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 rotate_image(img_src, angle,scale ,crop=True): img_src,size_dest= pad_image(img_src,scale) size = tuple(np.array([img_src.shape[1], img_src.shape[0]])) org_h=size[1] org_w=size[0] src_r = np.sqrt((size[0]/2.0)**2+(size[1]/2.0)**2) org_angle =np.arctan(float(org_h)/org_w) dest_h = size_dest[0] dest_w = size_dest[1] center = tuple(np.array([img_src.shape[1] * 0.5, img_src.shape[0] * 0.5])) dsize= (dest_w,dest_h) rotation_matrix = cv2.getRotationMatrix2D(center, angle, scale) img_rot = cv2.warpAffine(img_src, rotation_matrix, size, flags=cv2.INTER_CUBIC) if crop: x,y,w,h = cv2.boundingRect(img_rot[:,:,3]) return img_rot[y:y+h, x:x+w,:] else: return img_rot
def rotate_image(img_src, angle,scale ): img_src,size_dest= pad_image(img_src,scale) size = tuple(np.array([img_src.shape[1], img_src.shape[0]])) org_h=size[1] org_w=size[0] src_r = np.sqrt((size[0]/2.0)**2+(size[1]/2.0)**2) org_angle =np.arctan(float(org_h)/org_w) dest_h = size_dest[0] dest_w = size_dest[1] center = tuple(np.array([img_src.shape[1] * 0.5, img_src.shape[0] * 0.5])) dsize= (dest_w,dest_h) rotation_matrix = cv2.getRotationMatrix2D(center, angle, scale) img_rot = cv2.warpAffine(img_src, rotation_matrix, size, flags=cv2.INTER_CUBIC) x,y,w,h = cv2.boundingRect(img_rot[:,:,3]) return img_rot[y:y+h, x:x+w,:]
def cluster_bounding_boxes(self, contours): bounding_boxes = [] for i in range(len(contours)): x1,y1,w1,h1 = cv2.boundingRect(contours[i]) parent_bounding_box = self.get_parent_bounding_box(bounding_boxes, i) if parent_bounding_box is None: parent_bounding_box = self.BoundingBox(Rect(x1, y1, w1, h1)) parent_bounding_box.members.append(i) bounding_boxes.append(parent_bounding_box) for j in range(i+1, len(contours)): if self.get_parent_bounding_box(bounding_boxes, j) is None: x2,y2,w2,h2 = cv2.boundingRect(contours[j]) rect = Rect(x2, y2, w2, h2) distance = parent_bounding_box.rect.distance_to_rect(rect) if distance < 100: parent_bounding_box.update_rect(self.extend_rectangle(parent_bounding_box.rect, rect)) parent_bounding_box.members.append(j) return bounding_boxes
def extra_processing(pipeline): """ Performs extra processing on the pipeline's outputs and publishes data to NetworkTables. :param pipeline: the pipeline that just processed an image :return: None """ center_x_positions = [] center_y_positions = [] widths = [] heights = [] # Find the bounding boxes of the contours to get x, y, width, and height for contour in pipeline.filter_contours_output: x, y, w, h = cv2.boundingRect(contour) center_x_positions.append(x + w / 2) # X and Y are coordinates of the top-left corner of the bounding box center_y_positions.append(y + h / 2) widths.append(w) heights.append(y) # Publish to the '/vision' network table table = NetworkTable.getTable("/vision") table.putValue("centerX", NumberArray.from_list(center_x_positions)) table.putValue("centerY", NumberArray.from_list(center_y_positions)) table.putValue("width", NumberArray.from_list(widths)) table.putValue("height", NumberArray.from_list(heights))
def extra_processing(pipeline): """ Performs extra processing on the pipeline's outputs and publishes data to NetworkTables. :param pipeline: the pipeline that just processed an image :return: None """ center_x_positions = [] center_y_positions = [] widths = [] heights = [] # Find the bounding boxes of the contours to get x, y, width, and height for contour in pipeline.filter_contours_output: x, y, w, h = cv2.boundingRect(contour) center_x_positions.append(x + w / 2) # X and Y are coordinates of the top-left corner of the bounding box center_y_positions.append(y + h / 2) widths.append(w) heights.append(y) print(center_x_positions) # Publish to the '/vision' network table table = NetworkTable.getTable("/vision") table.putValue("centerX", NumberArray.from_list(center_x_positions)) table.putValue("centerY", NumberArray.from_list(center_y_positions)) table.putValue("width", NumberArray.from_list(widths)) table.putValue("height", NumberArray.from_list(heights))
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 get_contours(image, polydb=0.03, contour_range=5, show=False): # find the contours in the edged image, keeping only the largest ones, and initialize the screen contour # if cv2version == 3: im2, contours, hierarchy = cv2.findContours(image.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) contours = _findContours(image, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) cnts = sorted(contours, key = cv2.contourArea, reverse = True)[:contour_range] # loop over the contours screenCnt = None for c in cnts: # approximate the contour peri = cv2.arcLength(c, True) #finds the Contour Perimeter approx = cv2.approxPolyDP(c, polydb * peri, True) # if our approximated contour has four points, then we can assume that we have found our screen if len(approx) == 4: screenCnt = approx break if screenCnt is None: raise EdgeNotFound() # sometimes the algorythm finds a strange non-convex shape. The shape conforms to the card but its not complete, so then just complete the shape into a convex form if not cv2.isContourConvex(screenCnt): screenCnt = cv2.convexHull(screenCnt) x,y,w,h = cv2.boundingRect(screenCnt) screenCnt = np.array([[[x, y]], [[x+w, y]], [[x+w, y+h]], [[x, y+h]]]) if show: #this is for debugging puposes new_image = image.copy() cv2.drawContours(new_image, [screenCnt], -1, (255, 255, 0), 2) cv2.imshow("Contour1 image", new_image) cv2.waitKey(0) cv2.destroyAllWindows() return screenCnt
def get_contours(image, polydb=0.03, contour_range=5, show=False): # find the contours in the edged image, keeping only the largest ones, and initialize the screen contour if cv2version == 3: im2, contours, hierarchy = cv2.findContours(image.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) cnts = sorted(contours, key = cv2.contourArea, reverse = True)[:contour_range] # loop over the contours screenCnt = None for c in cnts: # approximate the contour peri = cv2.arcLength(c, True) #finds the Contour Perimeter approx = cv2.approxPolyDP(c, polydb * peri, True) # if our approximated contour has four points, then we can assume that we have found our screen if len(approx) == 4: screenCnt = approx break if screenCnt is None: raise EdgeNotFound() # sometimes the algorythm finds a strange non-convex shape. The shape conforms to the card but its not complete, so then just complete the shape into a convex form if not cv2.isContourConvex(screenCnt): screenCnt = cv2.convexHull(screenCnt) x,y,w,h = cv2.boundingRect(screenCnt) screenCnt = np.array([[[x, y]], [[x+w, y]], [[x+w, y+h]], [[x, y+h]]]) if show: #this is for debugging puposes new_image = image.copy() cv2.drawContours(new_image, [screenCnt], -1, (255, 255, 0), 2) cv2.imshow("Contour1 image", new_image) cv2.waitKey(0) cv2.destroyAllWindows() return screenCnt
def get_contours(image, polydb=0.1, contour_range=7, show=False): # find the contours in the edged image, keeping only the largest ones, and initialize the screen contour contours = _findContours(image, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) cnts = sorted(contours, key = cv2.contourArea, reverse = True)[:contour_range] # loop over the contours screenCnt = None for c in cnts: # approximate the contour peri = cv2.arcLength(c, True) #finds the Contour Perimeter approx = cv2.approxPolyDP(c, polydb * peri, True) # if our approximated contour has four points, then we can assume that we have found our screen if len(approx) == 4: screenCnt = approx break if screenCnt is None: raise EdgeNotFound() # sometimes the algorythm finds a strange non-convex shape. The shape conforms to the card but its not complete, so then just complete the shape into a convex form if not cv2.isContourConvex(screenCnt): screenCnt = cv2.convexHull(screenCnt) x,y,w,h = cv2.boundingRect(screenCnt) screenCnt = numpy.array([[[x, y]], [[x+w, y]], [[x+w, y+h]], [[x, y+h]]]) if show: #this is for debugging puposes new_image = image.copy() cv2.drawContours(new_image, [screenCnt], -1, (255, 255, 0), 2) cv2.imshow("Contour1 image", new_image) cv2.waitKey(0) cv2.destroyAllWindows() return screenCnt
def get_contours(image, polydb=0.03, contour_range=7, show=False): # find the contours in the edged image, keeping only the largest ones, and initialize the screen contour # if cv2version == 3: im2, contours, hierarchy = cv2.findContours(image.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) contours = _findContours(image, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) cnts = sorted(contours, key = cv2.contourArea, reverse = True)[:contour_range] # loop over the contours screenCnt = None for c in cnts: # approximate the contour peri = cv2.arcLength(c, True) #finds the Contour Perimeter approx = cv2.approxPolyDP(c, polydb * peri, True) # if our approximated contour has four points, then we can assume that we have found our screen if len(approx) == 4: screenCnt = approx break if screenCnt is None: raise EdgeNotFound() # sometimes the algorythm finds a strange non-convex shape. The shape conforms to the card but its not complete, so then just complete the shape into a convex form if not cv2.isContourConvex(screenCnt): screenCnt = cv2.convexHull(screenCnt) x,y,w,h = cv2.boundingRect(screenCnt) screenCnt = numpy.array([[[x, y]], [[x+w, y]], [[x+w, y+h]], [[x, y+h]]]) if show: #this is for debugging puposes new_image = image.copy() cv2.drawContours(new_image, [screenCnt], -1, (255, 255, 0), 2) cv2.imshow("Contour1 image", new_image) cv2.waitKey(0) cv2.destroyAllWindows() return screenCnt
def findFishingIcon(): #fish color low = np.array([93,119,84]) high = np.array([121,255,255]) mask, mm_x, mm_y = get_mini_map_mask(low, high) _, contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for c in contours: (x, y, w, h) = cv2.boundingRect(c) x += mm_x y += mm_y x2 = x + w y2 = y + h Mouse.randMove(x,y,x2,y2,1) run= 0 RandTime.randTime(1,0,0,1,9,9) return 0 return 1
def findFishingIcon(self): #fish color low = np.array([93,119,84]) high = np.array([121,255,255]) mask, mm_x, mm_y = self.mini_map_mask(low, high) _, contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for c in contours: (x, y, w, h) = cv2.boundingRect(c) x += mm_x y += mm_y x2 = x + w y2 = y + h Mouse.randMove(x,y,x2,y2,1) run= 0 time.sleep(1) return 0 return 1
def process_letter(thresh,output): # assign the kernel size kernel = np.ones((2,1), np.uint8) # vertical # use closing morph operation then erode to narrow the image temp_img = cv2.morphologyEx(thresh,cv2.MORPH_CLOSE,kernel,iterations=3) # temp_img = cv2.erode(thresh,kernel,iterations=2) letter_img = cv2.erode(temp_img,kernel,iterations=1) # find contours (contours, _) = cv2.findContours(letter_img.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) # loop in all the contour areas for cnt in contours: x,y,w,h = cv2.boundingRect(cnt) cv2.rectangle(output,(x-1,y-5),(x+w,y+h),(0,255,0),1) return output #processing letter by letter boxing