我们从Python开源项目中,提取了以下25个代码示例,用于说明如何使用cv2.ellipse()。
def draw_bboxes(vis, bboxes, texts=None, ellipse=False, colored=True): if not len(bboxes): return vis if not colored: cols = np.tile([240,240,240], [len(bboxes), 1]) else: N = 20 cwheel = colormap(np.linspace(0, 1, N)) cols = np.vstack([cwheel[idx % N] for idx, _ in enumerate(bboxes)]) texts = [None] * len(bboxes) if texts is None else texts for col, b, t in zip(cols, bboxes, texts): if ellipse: cv2.ellipse(vis, ((b[0]+b[2])/2, (b[1]+b[3])/2), ((b[2]-b[0])/2, (b[3]-b[1])/2), 0, 0, 360, color=tuple(col), thickness=1) else: cv2.rectangle(vis, (b[0], b[1]), (b[2], b[3]), tuple(col), 2) if t: annotate_bbox(vis, b, title=t) return vis
def getMask(self, shape): p=self.state['pos'] s=self.state['size'] center=p + s / 2 a=self.state['angle'] # opencv convention: shape = (shape[1], shape[0]) arr1 = np.zeros(shape, dtype=np.uint8) arr2 = np.zeros(shape, dtype=np.uint8) # draw rotated rectangle: vertices = np.int0(cv2.boxPoints((center, s, a))) cv2.drawContours(arr1, [vertices], 0, color=1, thickness=-1) # draw ellipse: cv2.ellipse(arr2, (int(center[0]), int(center[1])), (int(s[0] / 2 * self._ratioEllispeRectangle), int(s[1] / 2 * self._ratioEllispeRectangle)), int(a), startAngle=0, endAngle=360, color=1, thickness=-1) # bring both together: return np.logical_and(arr1, arr2).T
def getArrayRegion(self, arr, img=None): """ Return the result of ROI.getArrayRegion() masked by the elliptical shape of the ROI. Regions outside the ellipse are set to 0. """ # TODO: get right area for pseudosquare arr = pg.ROI.getArrayRegion(self, arr, img) if arr is None or arr.shape[0] == 0 or arr.shape[1] == 0: return None w = arr.shape[0] h = arr.shape[1] # generate an ellipsoidal mask mask = np.fromfunction(lambda x,y: ((((x+0.5)/((w/2.)))-1)**2+ ( ((y+0.5)/((h/2.)))-1)**2)**0.5 < self._ratioEllispeRectangle, (w, h)) return arr * mask
def getMask(self, shape): ''' returns bool array ''' p = self.state['pos'] s = self.state['size'] center = p + s / 2 a = self.state['angle'] # opencv convention: shape = (shape[1], shape[0]) arr = np.zeros(shape, dtype=np.uint8) # draw ellipse: cv2.ellipse(arr, (int(center[0]), int(center[1])), (int(s[0] / 2 * self._ratioEllispeRectangle), int(s[1] / 2 * self._ratioEllispeRectangle)), int(a), startAngle=0, endAngle=360, color=1, thickness=-1) return arr.astype(bool).T
def draw_face_ellipse(image, faces_coord): """ Draws an ellipse around the face found. """ for (x, y, w, h) in faces_coord: center = (x + w / 2, y + h / 2) axis_major = h / 2 axis_minor = w / 2 cv2.ellipse(image, center=center, axes=(axis_major, axis_minor), angle=0, startAngle=0, endAngle=360, color=(206, 0, 209), thickness=2) return image
def draw_ellipses(im, ellipses): for e in ellipses: cv2.ellipse(im, e, (255, 255, 0) if im.ndim == 3 else 255,1) return im
def gen_random_image(w,h): img = np.zeros((h, w, 3), dtype=np.uint8) mask = np.zeros((h, w), dtype=np.uint8) # Background dark_color0 = random.randint(0, 100) dark_color1 = random.randint(0, 100) dark_color2 = random.randint(0, 100) img[:, :, 0] = dark_color0 img[:, :, 1] = dark_color1 img[:, :, 2] = dark_color2 # Object light_color0 = random.randint(dark_color0+1, 255) light_color1 = random.randint(dark_color1+1, 255) light_color2 = random.randint(dark_color2+1, 255) center_0 = random.randint(0, h) center_1 = random.randint(0, w) r1 = random.randint(10, 56) r2 = random.randint(10, 56) cv2.ellipse(img, (center_0, center_1), (r1, r2), 0, 0, 360, (light_color0, light_color1, light_color2), -1) cv2.ellipse(mask, (center_0, center_1), (r1, r2), 0, 0, 360, 255, -1) # White noise density = random.uniform(0, 0.1) for i in range(h): for j in range(w): if random.random() < density: img[i, j, 0] = random.randint(0, 255) img[i, j, 1] = random.randint(0, 255) img[i, j, 2] = random.randint(0, 255) return img, mask
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 drawElipse(img, center, axes, angle, startAngle, endAngle, color, width): img = cv2.ellipse(img, center, axes, angle, startAngle, endAngle, color, width, cv2.LINE_AA) # ??????
def circle_contour(image, contour): # Bounding ellipse image_with_ellipse = image.copy() #easy function ellipse = cv2.fitEllipse(contour) #add it cv2.ellipse(image_with_ellipse, ellipse, green, 2,cv2.LINE_AA) return image_with_ellipse
def draw_arc(self): """Draw the arc that corresponds with the Neato's current projected path, based on current vel and omega.""" # If Neato is moving: if self.vel is not None and self.omega is not None: # If we are moving forward and turning: if self.omega != 0.0 and self.vel > 0.0: start_angle = 0 if self.omega > 0 else 180 end_angle = start_angle + 80 if self.omega < 0 else start_angle - 80 self.radius = (self.vel/self.omega)*500 radius_len = int(abs(self.radius)) #left wheel projection cv2.ellipse(img=self.arc_image, center=(int(HALF_WIDTH - self.radius - 150),IMG_HEIGHT), axes=(radius_len, radius_len), angle=0, startAngle=start_angle, endAngle= end_angle, color=(0, 0, 255), thickness=8) #right wheel projection cv2.ellipse(img=self.arc_image, center=(int(HALF_WIDTH - self.radius + 150),IMG_HEIGHT), axes=(radius_len, radius_len), angle=0, startAngle=start_angle, endAngle= end_angle, color=(0, 0, 255), thickness=8) # Otherwise we must be moving straight forwards else: if self.vel > 0.0: #should draw line cv2.line(self.arc_image,(170,IMG_HEIGHT),(170,200),self.color,6) cv2.line(self.arc_image,(470,IMG_HEIGHT),(470,200),self.color,6)
def _intersectionPointsAndAngles(r, ratioEllispeRectangle): ''' return all 8 x and y coords of lines build by intersection of ellipse and rect ''' w = r.width() h = r.height() x1 = 0.5 * w y2 = 0.5 * h # ellipse parameters: a = x1 * ratioEllispeRectangle b = y2 * ratioEllispeRectangle # intersection coords in the 1st quadrant with center=(0,0): y1 = ((1 - (x1**2 / a**2)) * b**2)**0.5 x2 = ((1 - (y2**2 / b**2)) * a**2)**0.5 c = r.center() cx = c.x() cy = c.y() # edge points: p1 = QtCore.QPointF(cx + x1, cy + y1) p2 = QtCore.QPointF(cx + x2, cy + y2) p3 = QtCore.QPointF(cx - x2, cy + y2) p4 = QtCore.QPointF(cx - x1, cy + y1) p5 = QtCore.QPointF(cx - x1, cy - y1) p6 = QtCore.QPointF(cx - x2, cy - y2) p7 = QtCore.QPointF(cx + x2, cy - y2) p8 = QtCore.QPointF(cx + x1, cy - y1) # angle in as degree*16 (needed in .drawArc) a1 = int(QtCore.QLineF(c, p1).angle() * 16) a2 = int(QtCore.QLineF(c, p2).angle() * 16) a4 = int(QtCore.QLineF(c, p4).angle() * 16) a6 = int(QtCore.QLineF(c, p6).angle() * 16) a8 = int(QtCore.QLineF(c, p8).angle() * 16) arc_length = a1 - a2 return (p1, p2, p3, p4, p5, p6, p7, p8), (a2, a4, a6, a8), arc_length
def gaussian(self, mean, covariance, label=None): """Draw 95% confidence ellipse of a 2-D Gaussian distribution. Parameters ---------- mean : array_like The mean vector of the Gaussian distribution (ndim=1). covariance : array_like The 2x2 covariance matrix of the Gaussian distribution. label : Optional[str] A text label that is placed at the center of the ellipse. """ # chi2inv(0.95, 2) = 5.9915 vals, vecs = np.linalg.eigh(5.9915 * covariance) indices = vals.argsort()[::-1] vals, vecs = np.sqrt(vals[indices]), vecs[:, indices] center = int(mean[0] + .5), int(mean[1] + .5) axes = int(vals[0] + .5), int(vals[1] + .5) angle = int(180. * np.arctan2(vecs[1, 0], vecs[0, 0]) / np.pi) cv2.ellipse( self.image, center, axes, angle, 0, 360, self._color, 2) if label is not None: cv2.putText(self.image, label, center, cv2.FONT_HERSHEY_PLAIN, 2, self.text_color, 2)
def generate( self ): # Create black background image and fill it up with random polygons img = np.zeros((self.height, self.width, 3), np.uint8) overlay = img.copy() output = img.copy() for i in range(self.size): info = self.genes[i].getInfo() if self.type == 1: cv2.circle(overlay,info[0], info[1], info[2], -1) cv2.addWeighted(overlay, info[3], output, 1 - info[3], 0, output) elif self.type == 2: cv2.ellipse(overlay,info[0],info[1],info[2],0,360,info[3],-1) cv2.addWeighted(overlay, info[4], output, 1 - info[4], 0, output) elif self.type == 3: cv2.fillConvexPoly(overlay,np.asarray(info[0]), info[1]) cv2.addWeighted(overlay, info[2], output, 1 - info[2], 0, output) elif self.type == 4: cv2.fillConvexPoly(overlay, np.asarray(info[0]), info[1]) cv2.addWeighted(overlay, info[2], output, 1 - info[2], 0, output ) return output
def DrawShape(img,matr,shape_type,shape_dimension,bubble_colour,bubble_linethickness): if shape_type==1: #1=rectangle/square for k in matr: imgoutput=cv2.rectangle(img,(k[0]-shape_dimension[0]/2,k[1]-shape_dimension[1]/2),(k[0]+shape_dimension[0]/2,k[1]+shape_dimension[1]/2),bubble_colour,bubble_linethickness) elif shape_type==2: #2=circle for k in matr: imgoutput=cv2.circle(img,(k[0],k[1]),int(shape_dimension[0]),bubble_colour,bubble_linethickness) elif shape_type == 3: # 2=oval for k in matr: imgoutput = cv2.ellipse(img, ((k[0], k[1]), (shape_dimension[0], shape_dimension[1]), 0), bubble_colour, bubble_linethickness) return imgoutput
def gen_random_image(): img = np.zeros((IMAGE_H, IMAGE_W, INPUT_CHANNELS), dtype=np.uint8) mask = np.zeros((IMAGE_H, IMAGE_W, NUMBER_OF_CLASSES), dtype=np.uint8) mask_obj1 = np.zeros((IMAGE_H, IMAGE_W, 1), dtype=np.uint8) colors = np.random.permutation(256) # Background img[:, :, 0] = colors[0] img[:, :, 1] = colors[1] img[:, :, 2] = colors[2] # Object class 1 obj1_color0 = colors[3] obj1_color1 = colors[4] obj1_color2 = colors[5] while(True): center_x = rn.randint(0, IMAGE_W) center_y = rn.randint(0, IMAGE_H) r_x = rn.randint(10, 50) r_y = rn.randint(10, 50) if(center_x+r_x < IMAGE_W and center_x-r_x > 0 and center_y+r_y < IMAGE_H and center_y-r_y > 0): cv2.ellipse(img, (int(center_x), int(center_y)), (int(r_x), int(r_y)), int(0), int(0), int(360), (int(obj1_color0), int(obj1_color1), int(obj1_color2)), int(-1)) cv2.ellipse(mask_obj1, (int(center_x), int(center_y)), (int(r_x), int(r_y)), int(0), int(0), int(360), int(255), int(-1)) break mask[:,:,0] = np.squeeze(mask_obj1) mask[:,:,1] = np.squeeze(cv2.bitwise_not(mask_obj1)) # White noise density = rn.uniform(0, 0.1) for i in range(IMAGE_H): for j in range(IMAGE_W): if rn.random() < density: img[i, j, 0] = rn.randint(0, 255) img[i, j, 1] = rn.randint(0, 255) img[i, j, 2] = rn.randint(0, 255) return img, mask
def gen_random_image(): img = np.zeros((IMAGE_H, IMAGE_W, INPUT_CHANNELS), dtype=np.uint8) mask = np.zeros((IMAGE_H, IMAGE_W, NUMBER_OF_CLASSES), dtype=np.uint8) colors = np.random.permutation(256) # Background img[:, :, 0] = colors[0] img[:, :, 1] = colors[1] img[:, :, 2] = colors[2] # Object class 1 obj1_color0 = colors[3] obj1_color1 = colors[4] obj1_color2 = colors[5] while(True): center_x = rn.randint(0, IMAGE_W) center_y = rn.randint(0, IMAGE_H) r_x = rn.randint(10, 50) r_y = rn.randint(10, 50) if(center_x+r_x < IMAGE_W and center_x-r_x > 0 and center_y+r_y < IMAGE_H and center_y-r_y > 0): cv2.ellipse(img, (int(center_x), int(center_y)), (int(r_x), int(r_y)), int(0), int(0), int(360), (int(obj1_color0), int(obj1_color1), int(obj1_color2)), int(-1)) cv2.ellipse(mask, (int(center_x), int(center_y)), (int(r_x), int(r_y)), int(0), int(0), int(360), int(255), int(-1)) break # White noise density = rn.uniform(0, 0.1) for i in range(IMAGE_H): for j in range(IMAGE_W): if rn.random() < density: img[i, j, 0] = rn.randint(0, 255) img[i, j, 1] = rn.randint(0, 255) img[i, j, 2] = rn.randint(0, 255) return img, mask
def cut_face_ellipse(image, face_coord): """ Cuts the image to just show the face in an ellipse. This function takes the rectangle coordinates around a detected face or faces and cuts the original image with the face coordenates. It also surrounds the face with an ellipse making black all the extra background or faces """ images_ellipse = [] for (x, y, w, h) in face_coord: center = (x + w / 2, y + h / 2) axis_major = (h / 2) axis_minor = (w / 2) mask = np.zeros_like(image) # create a white filled ellipse mask = cv2.ellipse(mask, center=center, axes=(axis_major, axis_minor), angle=0, startAngle=0, endAngle=360, color=(255, 255, 255), thickness=-1) # Bitwise AND operation to black out regions outside the mask image_ellipse = np.bitwise_and(image, mask) images_ellipse.append(image_ellipse[y: y + h, x: x + w]) return images_ellipse
def draw_groupRect(self, img_arr, ID): ID = int(ID) img = Image.fromarray(img_arr) draw = ImageDraw.Draw(img, mode='RGBA') bi_ID = bi_t = np.zeros(self.final_BI.shape, np.uint8) bi_ID[self.final_ID == ID] = 255 # Image.fromarray(bi_ID).show() ## get contour -- cnt of polygon if self.parent().line2_mode == "polygonOtsu": bi_ID = cv2.GaussianBlur(bi_ID, (11, 11), 0) bi_ID = cv2.dilate(bi_ID, None, iterations=4) im2, contours, hierarchy = cv2.findContours(bi_ID, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnt_union = contours[0] for i, cnt in enumerate(contours): if i > 0: cnt_union = np.concatenate((cnt_union, cnt), axis=0) ellipse = cv2.fitEllipse(cnt_union) cv2.ellipse(img_arr,ellipse,(0,255,0,175),2) extBottom = tuple(cnt_union[cnt_union[:, :, 1].argmax()][0]) font = cv2.FONT_HERSHEY_PLAIN cv2.putText(img_arr, "ID_"+str(ID), extBottom, font, 1.5, (255, 49, 12), 2) return img_arr
def rounded_rectangle(src, topLeft, bottomRight, lineColor, thickness=1, lineType=cv.CV_AA , cornerRadius=10): #/* corners: # * p1 - p2 # * | | # * p4 - p3 # */ p1 = topLeft; p2 = (bottomRight[0], topLeft[1]); p3 = bottomRight; p4 = (topLeft[0], bottomRight[1]); #// draw straight lines cv2.line(src, (p1[0]+cornerRadius,p1[1]), (p2[0]-cornerRadius,p2[1]), lineColor, thickness, lineType); cv2.line(src,(p2[0],p2[1]+cornerRadius), (p3[0],p3[1]-cornerRadius), lineColor, thickness, lineType); cv2.line(src, (p4[0]+cornerRadius,p4[1]), (p3[0]-cornerRadius,p3[1]), lineColor, thickness, lineType); cv2.line(src, (p1[0],p1[1]+cornerRadius), (p4[0],p4[1]-cornerRadius), lineColor, thickness, lineType); #// draw arcs cv2.ellipse( src, tuple(np.add(p1, (cornerRadius, cornerRadius))), ( cornerRadius, cornerRadius ), 180, 0, 90, lineColor, thickness, lineType ); cv2.ellipse( src, tuple(np.add(p2, (-cornerRadius, cornerRadius))), ( cornerRadius, cornerRadius ), 270, 0, 90, lineColor, thickness, lineType ); cv2.ellipse( src, tuple(np.add(p3, (-cornerRadius, -cornerRadius))), ( cornerRadius, cornerRadius ), 0, 0, 90, lineColor, thickness, lineType ); cv2.ellipse( src, tuple(np.add(p4, (cornerRadius, -cornerRadius))), ( cornerRadius, cornerRadius ), 90, 0, 90, lineColor, thickness, lineType );
def gen_random_image(): img = np.zeros((224, 224, 3), dtype=np.uint8) mask = np.zeros((224, 224), dtype=np.uint8) # Background dark_color0 = random.randint(0, 100) dark_color1 = random.randint(0, 100) dark_color2 = random.randint(0, 100) img[:, :, 0] = dark_color0 img[:, :, 1] = dark_color1 img[:, :, 2] = dark_color2 # Object light_color0 = random.randint(dark_color0+1, 255) light_color1 = random.randint(dark_color1+1, 255) light_color2 = random.randint(dark_color2+1, 255) center_0 = random.randint(0, 224) center_1 = random.randint(0, 224) r1 = random.randint(10, 56) r2 = random.randint(10, 56) cv2.ellipse(img, (center_0, center_1), (r1, r2), 0, 0, 360, (light_color0, light_color1, light_color2), -1) cv2.ellipse(mask, (center_0, center_1), (r1, r2), 0, 0, 360, 255, -1) # White noise density = random.uniform(0, 0.1) for i in range(224): for j in range(224): if random.random() < density: img[i, j, 0] = random.randint(0, 255) img[i, j, 1] = random.randint(0, 255) img[i, j, 2] = random.randint(0, 255) return img, mask
def run ( self ): # Succesively add a new polygon that contributes to reduce overall error # until stopping criteria is achieved min_err = self.fitness( self.source ) cur = copy.deepcopy( self.source ) improvements = 0 for i in range ( self.iterations ): next = copy.deepcopy(cur) if self.type == 1: c = circle.Circle(self.height,self.width, 0.1) info = c.getInfo() cv2.circle(cur,info[0], info[1], info[2], -1) cv2.addWeighted(cur, info[3], next, 1 - info[3], 0, next) elif self.type == 2: e = ellipse.Ellipse(self.height,self.width, 0.1) info = e.getInfo() cv2.ellipse(cur,info[0],info[1],info[2],0,360,info[3],-1) cv2.addWeighted(cur, info[4], next, 1 - info[4], 0, next) elif self.type == 3: t = triangle.Triangle(self.height,self.width, 0.1) info = t.getInfo() cv2.fillConvexPoly(cur,np.asarray(info[0]), info[1]) cv2.addWeighted(cur, info[2], next, 1 - info[2], 0, next) elif self.type == 4: r = quadrilateral.Quadrilateral(self.height,self.width, 0.1) info = r.getInfo() cv2.fillConvexPoly(cur, np.asarray(info[0]), info[1]) cv2.addWeighted(cur, info[2], next, 1 - info[2], 0, next) # Compute dissimilarity err = self.fitness(next) # Update the solution that provides more fitness if err < min_err : min_err = err improvements = improvements + 1 cur = copy.deepcopy(next) cv2.imwrite("Refine_Error_" + str(i) + "_" + str(min_err) + ".jpg", cur) if improvements == self.maximprovements: break
def gen_random_image(): img = np.zeros((IMAGE_H, IMAGE_W, INPUT_CHANNELS), dtype=np.uint8) mask = np.zeros((IMAGE_H, IMAGE_W, NUMBER_OF_CLASSES), dtype=np.uint8) mask_obj1 = np.zeros((IMAGE_H, IMAGE_W, 1), dtype=np.uint8) mask_obj2 = np.zeros((IMAGE_H, IMAGE_W, 1), dtype=np.uint8) colors = np.random.permutation(256) # Background img[:, :, 0] = colors[0] img[:, :, 1] = colors[1] img[:, :, 2] = colors[2] # Object class 1 obj1_color0 = colors[3] obj1_color1 = colors[4] obj1_color2 = colors[5] while(True): center_x = rn.randint(0, IMAGE_W) center_y = rn.randint(0, IMAGE_H) r_x = rn.randint(10, 50) r_y = rn.randint(10, 50) if(center_x+r_x < IMAGE_W and center_x-r_x > 0 and center_y+r_y < IMAGE_H and center_y-r_y > 0): cv2.ellipse(img, (int(center_x), int(center_y)), (int(r_x), int(r_y)), int(0), int(0), int(360), (int(obj1_color0), int(obj1_color1), int(obj1_color2)), int(-1)) cv2.ellipse(mask_obj1, (int(center_x), int(center_y)), (int(r_x), int(r_y)), int(0), int(0), int(360), int(255), int(-1)) break # Object class 2 obj2_color0 = colors[6] obj2_color1 = colors[7] obj2_color2 = colors[8] while(True): left = rn.randint(0, IMAGE_W) top = rn.randint(0, IMAGE_H) dw = rn.randint(int(10*math.pi), int(50*math.pi)) dh = rn.randint(int(10*math.pi), int(50*math.pi)) if(left+dw < IMAGE_W and top+dh < IMAGE_H): mask_obj2 = np.zeros((IMAGE_H, IMAGE_W, 1), dtype=np.uint8) cv2.rectangle(mask_obj2, (left, top), (left+dw, top+dh), 255, -1) if(np.sum(cv2.bitwise_and(mask_obj1,mask_obj2)) == 0): cv2.rectangle(img, (left, top), (left+dw, top+dh), (obj2_color0, obj2_color1, obj2_color2), -1) break mask[:,:,0] = np.squeeze(mask_obj1) mask[:,:,1] = np.squeeze(mask_obj2) mask[:,:,2] = cv2.bitwise_not(cv2.bitwise_or(mask_obj1,mask_obj2)) # White noise density = rn.uniform(0, 0.1) for i in range(IMAGE_H): for j in range(IMAGE_W): if rn.random() < density: img[i, j, 0] = rn.randint(0, 255) img[i, j, 1] = rn.randint(0, 255) img[i, j, 2] = rn.randint(0, 255) return img, mask
def gen_random_image(): img = np.zeros((IMAGE_H, IMAGE_W, INPUT_CHANNELS), dtype=np.uint8) mask = np.zeros((IMAGE_H, IMAGE_W, NUMBER_OF_CLASSES), dtype=np.uint8) mask_obj1 = np.zeros((IMAGE_H, IMAGE_W, 1), dtype=np.uint8) mask_obj2 = np.zeros((IMAGE_H, IMAGE_W, 1), dtype=np.uint8) colors = np.random.permutation(256) # Background img[:, :, 0] = colors[0] img[:, :, 1] = colors[1] img[:, :, 2] = colors[2] # Object class 1 obj1_color0 = colors[3] obj1_color1 = colors[4] obj1_color2 = colors[5] while(True): center_x = rn.randint(0, IMAGE_W) center_y = rn.randint(0, IMAGE_H) r_x = rn.randint(10, 50) r_y = rn.randint(10, 50) if(center_x+r_x < IMAGE_W and center_x-r_x > 0 and center_y+r_y < IMAGE_H and center_y-r_y > 0): cv2.ellipse(img, (int(center_x), int(center_y)), (int(r_x), int(r_y)), int(0), int(0), int(360), (int(obj1_color0), int(obj1_color1), int(obj1_color2)), int(-1)) cv2.ellipse(mask_obj1, (int(center_x), int(center_y)), (int(r_x), int(r_y)), int(0), int(0), int(360), int(255), int(-1)) break # Object class 2 obj2_color0 = colors[6] obj2_color1 = colors[7] obj2_color2 = colors[8] while(True): left = rn.randint(0, IMAGE_W) top = rn.randint(0, IMAGE_H) dw = rn.randint(int(10*math.pi), int(50*math.pi)) dh = rn.randint(int(10*math.pi), int(50*math.pi)) if(left+dw < IMAGE_W and top+dh < IMAGE_H): mask_obj2 = np.zeros((IMAGE_H, IMAGE_W, 1), dtype=np.uint8) cv2.rectangle(mask_obj2, (left, top), (left+dw, top+dh), 255, -1) if(np.sum(cv2.bitwise_and(mask_obj1,mask_obj2)) == 0): cv2.rectangle(img, (left, top), (left+dw, top+dh), (obj2_color0, obj2_color1, obj2_color2), -1) break mask[:,:,0] = np.squeeze(mask_obj1) mask[:,:,1] = np.squeeze(mask_obj2) # White noise density = rn.uniform(0, 0.1) for i in range(IMAGE_H): for j in range(IMAGE_W): if rn.random() < density: img[i, j, 0] = rn.randint(0, 255) img[i, j, 1] = rn.randint(0, 255) img[i, j, 2] = rn.randint(0, 255) return img, mask
def fit_ellipse(masks): ellipses = [] k = 0 for i in range(0,len(masks)): mask = masks[0] #cv2.imwrite("./input/ellipses/10_1_"+str(k)+"_mask.tif", mask) contours, hierarchy = cv2.findContours(mask.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE) #immagine nera temp = np.zeros(mask.shape, dtype=np.uint8) #cv2.imwrite("./input/ellipses/10_1_mask_black.tif", temp) #disegno i contorni su sfondo nero cv2.drawContours(temp, contours, -1, (255,255,255), 3) #voglio scrivere quest'immagine che, in teoria, e' nera con #i contorni individuati in bianco.. ma esplode il kernel se usata #cv2.imwrite("./input/ellipses/10_1_mask_cont.tif", temp) #cv2.imwrite("./input/ellipses/10_1_mask_after.tif", mask) for cnt in contours: param_ellipse = [] #print "fitto" ellipse = cv2.fitEllipse(cnt) #cv2.imwrite("./input/ellipses/10_1_"+str(k)+"_mask.tif", mask) #disegna l'ellisse black = np.zeros(mask.shape, dtype=np.uint8) cv2.ellipse(black, ellipse, (255,255,255), 2) #cv2.imwrite("./input/ellipses/10_1_"+str(k)+"_mask_ellipse.tif", black) k=k+1 ''' Coordinate necessarie/ritornate: (ellipse.center.x, ellipse.center.y), (ellipse.size.height*2, ellipse.size.width*2), ellipse.angle ''' #print "ellipse" #print ellipse ellipses.append(ellipse) return np.array(ellipses)