def analyze_lowexp(self): try: summed = np.add(np.add(self.img[:, :, 0], self.img[:, :, 1]), self.img[:, :, 2]) smoothed = filters.gaussian(summed, 5) mask = cutoff(smoothed, self.specs) edges = filters.sobel(mask) # Detect two radii hough_radii = np.arange(CAPILLARY_DIAM_LOW_BOUND, CAPILLARY_DIAM_UP_BOUND, 2) hough_res = trans.hough_circle(edges, hough_radii) print('\tcalculating hough transform...') # Select the most prominent 1 circles accums, cx, cy, radii = trans.hough_circle_peaks(hough_res, hough_radii, total_num_peaks=1) self.cap_x = cx[0] self.cap_y = cy[0] self.cap_r = radii[0] # Detect two radii hough_radii = np.arange(self.specs[1], self.specs[2], 2) hough_res = trans.hough_circle(edges, hough_radii) # Select the most prominent 5 circles accums, cx, cy, radii = trans.hough_circle_peaks(hough_res, hough_radii, total_num_peaks=1) print("\tbore - accums, cx, cy, radii " + str((accums, cx, cy, radii))) self.bore_x = cx[0] self.bore_y = cy[0] self.bore_r = radii[0] self.axes.imshow(self.img) self.axes.add_patch( Circle((self.bore_x, self.bore_y), self.bore_r, color='r', fill=False)) self.axes.add_patch( Circle((self.cap_x, self.cap_y), self.cap_r, color='r', fill=False)) except: raise ValueError("Failed during lowexp analysis of img: " + str(self.name)) raise ''' ---------------------------- additional methods ----------------------- ''' """
def analyze_otsu(self): try: # convert to grey grey = color.rgb2gray(self.img) #smooth to remove noise, high noise makes hough transform take significantly more time grey_smooth = filters.gaussian(grey, 3) # threshold via otsu histogram binning otsu = grey_smooth > filters.threshold_otsu(grey_smooth) # calculate edges via sobel method edges = filters.sobel(otsu) print('\tcalculating hough transform...') # Detect two radii hough_radii = np.arange(CAPILLARY_DIAM_LOW_BOUND, CAPILLARY_DIAM_UP_BOUND, 2) hough_res = trans.hough_circle(edges, hough_radii) # Select the most prominent circle accums, cx, cy, radii = trans.hough_circle_peaks(hough_res, hough_radii, total_num_peaks=1) self.cap_x = cx[0] self.cap_y = cy[0] self.cap_r = radii[0] # Detect two radii hough_radii = np.arange(self.specs[1], self.specs[2], 2) hough_res = trans.hough_circle(edges, hough_radii) # Select the most prominent circle accums, cx, cy, radii = trans.hough_circle_peaks(hough_res, hough_radii, total_num_peaks=1) print("\taccums, cx, cy, radii " + str((accums, cx, cy, radii))) self.bore_x = cx[0] self.bore_y = cy[0] self.bore_r = radii[0] self.axes.imshow(self.img) self.axes.set_title(str(self.name)) self.axes.add_patch( Circle((self.bore_x, self.bore_y), self.bore_r, color='r', fill=False)) self.axes.add_patch( Circle((self.cap_x, self.cap_y), self.cap_r, color='r', fill=False)) except: raise ValueError("Failed during Otsu analysis of img: " + str(self.name)) raise
def get_circle_locations(image, name, outputs, specs): try: summed = np.add(image[:,:,0], image[:,:,1]) summed = np.add(summed, image[:,:,2]) smoothed = filters.gaussian(summed, 5) mask = cutoff(smoothed, specs) # plt.imshow(mask) # plt.show() edges = filters.sobel(mask) # Detect two radii hough_radii = np.arange(CAPILLARY_DIAM_LOW_BOUND, CAPILLARY_DIAM_UP_BOUND, 2) hough_res = trans.hough_circle(edges, hough_radii) # Select the most prominent 1 circles accums, cx, cy, radii = trans.hough_circle_peaks(hough_res, hough_radii, total_num_peaks=1) cap_x = cx[0] cap_y = cy[0] cap_r = radii[0] # Detect two radii hough_radii = np.arange(specs[1], specs[2], 2) hough_res = trans.hough_circle(edges, hough_radii) # Select the most prominent 5 circles accums, cx, cy, radii = trans.hough_circle_peaks(hough_res, hough_radii, total_num_peaks=1) print("accums, cx, cy, radii " + str( (accums, cx, cy, radii) )) bore_x = cx[0] bore_y = cy[0] bore_r = radii[0] fig1, ax1 = plt.subplots(ncols=1, nrows=1, figsize=(10, 4)) ax1.imshow(image) ax1.add_patch(Circle((bore_x,bore_y),bore_r, color='r', fill=False)) ax1.add_patch(Circle((cap_x,cap_y),cap_r, color='r', fill=False)) fig1.savefig(outputs+'\\'+name[:-4]+'-circled.png') plt.close('all') return (cap_x, cap_y, cap_r), (bore_x,bore_y,bore_r) except: print('failed at ' + str(name)) print('expected outputs ' + str(outputs)) print() raise
def find_circles(binary_patch): # Get size of the patch min_image_size = min(binary_patch.shape[0], binary_patch.shape[1]) max_image_size = max(binary_patch.shape[0], binary_patch.shape[1]) # Determine min and max radius based on patch size min_radius = max(10, int(min_image_size / 4)) max_radius = int(max_image_size / 2) hough_radii = np.arange(min_radius, max_radius) # Apply Hough circle transform hough_res = hough_circle(binary_patch, hough_radii) # Set parameters for hough_circle_peaks min_distance = int(max_image_size / 3) threshold = 0.6 num_peaks = np.inf total_num_peaks = 5 normalize = True # Filter result of Hough circle transform based on parameters _, cx, cy, radii = hough_circle_peaks(hough_res, hough_radii, min_distance, min_distance, threshold, num_peaks, total_num_peaks, normalize) detected_circles = zip(cx, cy, radii) # Return found circles return detected_circles
def circular_hough_transform(r1, r2, step, edge, peak_num): hough_radii = np.arange(r1, r2, step) hough_res = hough_circle(edge, hough_radii) accums, cx, cy, radii = hough_circle_peaks(hough_res, hough_radii, total_num_peaks=peak_num) return accums, cx, cy, radii
def analyze_ra_rotation(rotate_fn): """ Get RA axis center of rotation XY coordinates Args: rotate_fn (str): FITS file of RA rotation Returns: tuple(int): A tuple of integers corresponding to the XY pixel position of the center of rotation around RA axis """ d0 = fits.getdata(rotate_fn) # - 2048 # Get center position = (d0.shape[1] // 2, d0.shape[0] // 2) size = (1500, 1500) d1 = Cutout2D(d0, position, size) d1.data = d1.data / d1.data.max() # Get edges for rotation rotate_edges = canny(d1.data, sigma=1.0) rotate_hough_radii = np.arange(100, 500, 50) rotate_hough_res = hough_circle(rotate_edges, rotate_hough_radii) rotate_accums, rotate_cx, rotate_cy, rotate_radii = \ hough_circle_peaks(rotate_hough_res, rotate_hough_radii, total_num_peaks=1) return d1.to_original_position((rotate_cx[-1], rotate_cy[-1]))
def find_circle(noisy_img, model): # Fill in this function noisy_img = np.expand_dims(np.expand_dims(noisy_img, axis=0), axis=-1) img = model.predict(noisy_img / np.amax(noisy_img)).reshape(IMAGE_SIZE, IMAGE_SIZE) edges = canny(img, low_threshold=0.5, high_threshold=1.0) try_radii = np.arange(10, MAX_RAD, 1) hough_res = hough_circle(edges, try_radii) _, cy, cx, radii = hough_circle_peaks(hough_res, try_radii, total_num_peaks=1) if cx.size == 0: cx = 0 else: cx = cx[-1] if cy.size == 0: cy = 0 else: cy = cy[-1] if radii.size == 0: radii = 0 else: radii = radii[-1] return (cx, cy, radii)
def _detect_nodes(edges, node_radius: Tuple[int, int], num_nodes: int, n): """ """ from skimage.transform import hough_circle, hough_circle_peaks from skimage import color from skimage.draw import circle_perimeter nodes = [] hough_radii = np.arange(node_radius[0], node_radius[1], 1) hough_res = hough_circle(edges, hough_radii) accums, cx, cy, radii = hough_circle_peaks(hough_res, hough_radii, total_num_peaks=num_nodes) # fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(10, 10)) # image = color.gray2rgb(img.copy()) i = 0 for center_y, center_x, radius in zip(cy, cx, radii): # circy, circx = circle_perimeter(center_y, center_x, radius, # shape=image.shape) # image[circy, circx] = (255, 20, 20) n.add_node(str(i), x=center_x, y=center_y, r=radius, coordinates=(center_x, -center_y)) i += 1
def test_hough_circle_peaks_min_distance(): x_0, y_0, rad_0 = (50, 50, 20) img = np.zeros((120, 100), dtype=int) y, x = circle_perimeter(y_0, x_0, rad_0) img[x, y] = 1 x_1, y_1, rad_1 = (60, 60, 30) y, x = circle_perimeter(y_1, x_1, rad_1) # Add noise and create an imperfect circle to lower the peak in Hough space y[::2] += 1 x[::2] += 1 img[x, y] = 1 x_2, y_2, rad_2 = (70, 70, 20) y, x = circle_perimeter(y_2, x_2, rad_2) # Add noise and create an imperfect circle to lower the peak in Hough space y[::2] += 1 x[::2] += 1 img[x, y] = 1 radii = [rad_0, rad_1, rad_2] hspaces = transform.hough_circle(img, radii) out = transform.hough_circle_peaks(hspaces, radii, min_xdistance=15, min_ydistance=15, threshold=None, num_peaks=np.inf, total_num_peaks=np.inf, normalize=True) # The second circle is too close to the first one # and has a weaker peak in Hough space due to imperfectness. # Therefore it got removed. assert_equal(out[1], np.array([y_0, y_2])) assert_equal(out[2], np.array([x_0, x_2])) assert_equal(out[3], np.array([rad_0, rad_2]))
def electrode_detection(input_path, output_path): # approach one, using cv2 img = cv.imread(input_path, 0) # Load picture and detect edges edges = canny(img, sigma=2, low_threshold=35, high_threshold=40) #plot the graph to get a better feeling """ fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(10, 10)) ax.imshow(edges, cmap=plt.cm.gray) plt.show() """ # Detect circles with size of hough_radii hough_radii = np.arange(5, 40, 1) hough_res = hough_circle(edges, hough_radii) # Select the most prominent 30 circles accums, cx, cy, radii = hough_circle_peaks(hough_res, hough_radii, total_num_peaks=30) #this returns the list of points that are on the perimeters, and change the value to white #for better visualization fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(10, 10)) for center_y, center_x, radius in zip(cy, cx, radii): circy, circx = circle_perimeter(center_y, center_x, radius, shape=img.shape) img[circy, circx] = 255 ax.imshow(img, cmap=plt.cm.gray) plt.show() #np.save(output_path, list(zip(cy,cx))) np.savetxt(output_path, list(zip(cy, cx)), fmt='%s') return list(zip(cy, cx))
def find_circles(edge_img, min_radius, max_radius): hough_radii = np.arange(min_radius, max_radius, 2) hough_res = hough_circle(edge_img, hough_radii) accums, cx, cy, radii = hough_circle_peaks(hough_res, hough_radii, total_num_peaks=1) return list(zip(cy, cx, radii))
def test_hough_circle_peaks_total_peak(): img = np.zeros((120, 100), dtype=int) x_0, y_0, rad_0 = (99, 50, 20) y, x = circle_perimeter(y_0, x_0, rad_0) img[x, y] = 1 x_1, y_1, rad_1 = (49, 60, 30) y, x = circle_perimeter(y_1, x_1, rad_1) img[x, y] = 1 radii = [rad_0, rad_1] hspaces = transform.hough_circle(img, radii) out = transform.hough_circle_peaks(hspaces, radii, min_xdistance=1, min_ydistance=1, threshold=None, num_peaks=np.inf, total_num_peaks=1) assert_equal(out[1][0], np.array([ y_1, ])) assert_equal(out[2][0], np.array([ x_1, ])) assert_equal(out[3][0], np.array([ rad_1, ]))
def test_hough_circle_peaks_normalize(): x_0, y_0, rad_0 = (50, 50, 20) img = np.zeros((120, 100), dtype=int) y, x = circle_perimeter(y_0, x_0, rad_0) img[x, y] = 1 x_1, y_1, rad_1 = (60, 60, 30) y, x = circle_perimeter(y_1, x_1, rad_1) img[x, y] = 1 radii = [rad_0, rad_1] hspaces = transform.hough_circle(img, radii) out = transform.hough_circle_peaks(hspaces, radii, min_xdistance=15, min_ydistance=15, threshold=None, num_peaks=np.inf, total_num_peaks=np.inf, normalize=False) # Two perfect circles are close but the second one is bigger. # Therefore, it is picked due to its high peak. assert_equal(out[1], np.array([y_1])) assert_equal(out[2], np.array([x_1])) assert_equal(out[3], np.array([rad_1]))
def processImage(imgNumber = -1): if imgNumber > -1: greyimage = rgb2gray(io.imread("data/{img}.JPG".format(img=imgNumber))) greyimage = greyimage > .5 else: greyimage = data.coins() image = img_as_ubyte(greyimage) edges = sobel(image) edges = mp.dilation(canny(image, sigma=3, low_threshold=30, high_threshold=60)) drawPlot(edges) # Detect two radii hough_radii = np.arange(100, 250, 20) hough_res = hough_circle(edges, hough_radii) # Select the most prominent 5 circles accums, cx, cy, radii = hough_circle_peaks(hough_res, hough_radii, total_num_peaks=20) # Draw them image = color.gray2rgb(image) for center_y, center_x, radius in zip(cy, cx, radii): circy, circx = circle_perimeter(center_y, center_x, radius) image[circy, circx] = (220, 20, 20) drawPlot(image)
def get_best_circles(mask, resize_factor=8): ''' Get the best the best fit to a circle using the hough transform. ''' #%% #resize image to increase speed. I don't want #%% min_size = min(mask.shape) resize_factor = min_size / max(128, min_size / resize_factor) dsize = tuple(int(x / resize_factor) for x in mask.shape[::-1]) mask_s = cv2.dilate(mask, disk(resize_factor / 2)) mask_s = cv2.resize(mask_s, dsize) #%% r_min = min(mask_s.shape) r_max = max(mask_s.shape) #use the first peak of the circle hough transform to initialize the food shape hough_radii = np.arange(r_min / 4, r_max / 2, 2) hough_res = hough_circle(mask_s, hough_radii) accums, cx, cy, radii = hough_circle_peaks(hough_res, hough_radii, total_num_peaks=9) #%% cx, cy, radii = [ np.round(x * resize_factor).astype(np.int) for x in (cx, cy, radii) ] #%% return list(zip(accums, cx, cy, radii))
def reshape_image(raw_patient): #generate pixels # approach one, using cv2 img = cv2.imread(raw_patient, 0) # Load picture and detect edges edges = canny(img, sigma=3, low_threshold=10, high_threshold=50) # Detect two radii hough_radii = np.arange(200, 600, 1) hough_res = hough_circle(edges, hough_radii) # Select the most prominent 1 circles accums, cx, cy, radii = hough_circle_peaks(hough_res, hough_radii, total_num_peaks=1) mask_internal = np.zeros((2 * radii[0], 2 * radii[0]), dtype=np.uint8) y_min = cy[0] - radii[0] x_min = cx[0] - radii[0] #filtering the ones only in the pixels for y in range(0, (2 * radii[0])): for x in range(0, (2 * radii[0])): mask_internal[y, x] = img[y + y_min, x + x_min] # change the internal white pixels to black for y in range(0, (2 * radii[0])): for x in range(0, (2 * radii[0])): if mask_internal[y, x] >= white_pixel_min and mask_internal[ y, x] <= white_pixel_max: mask_internal[y, x] = black_pixel #np.save('Data/Modified_fluoro2/patient_'+str(i)+'.npy', mask_internal) return (mask_internal, (y_min, x_min), radii[0])
def analyze_ra_rotation(rotate_fn): """ Get RA axis center of rotation XY coordinates Args: rotate_fn (str): FITS file of RA rotation Returns: tuple(int): A tuple of integers corresponding to the XY pixel position of the center of rotation around RA axis """ d0 = fits.getdata(rotate_fn) # - 2048 # Get center position = (d0.shape[1] // 2, d0.shape[0] // 2) size = (1500, 1500) d1 = Cutout2D(d0, position, size) d1.data = d1.data / d1.data.max() # Get edges for rotation rotate_edges = canny(d1.data, sigma=1.0) rotate_hough_radii = np.arange(100, 500, 50) rotate_hough_res = hough_circle(rotate_edges, rotate_hough_radii) rotate_accums, rotate_cx, rotate_cy, rotate_radii = \ hough_circle_peaks(rotate_hough_res, rotate_hough_radii, total_num_peaks=1) return d1.to_original_position((rotate_cx[-1], rotate_cy[-1]))
def find_plate2(path): # Load picture and detect edges image_rgb = io.imread(path) image = color.rgb2gray(image_rgb) # image = resize(image, (100, 100)) image = rescale(image, 0.1) edges = canny(image, sigma=2, low_threshold=0.40, high_threshold=0.80) plt.imshow(edges) plt.show() # Detect two radii hough_radii = np.arange(20, 60, 2) hough_res = hough_circle(edges, hough_radii) # Select the most prominent 5 circles accums, cx, cy, radii = hough_circle_peaks(hough_res, hough_radii, total_num_peaks=3) # Draw them fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(10, 4)) image = color.gray2rgb(image) for center_y, center_x, radius in zip(cy, cx, radii): circy, circx = circle_perimeter(center_y, center_x, radius) try: image[circy, circx] = (220, 20, 20) except IndexError as e: print(e) ax.imshow(image, cmap=plt.cm.gray) plt.show()
def find_the_ball(nome): pasta = 'processing/img_recortadas/' im = io.imread(pasta + nome) im2 = im.copy() noisy_image = img_as_ubyte(im2[:,:,0]) noise = np.random.random(noisy_image.shape) noisy_image[noise > 0.99] = 255 noisy_image[noise < 0.01] = 0 im[:,:,0] = median(noisy_image, disk(1)) noisy_image = img_as_ubyte(im2[:,:,1]) noise = np.random.random(noisy_image.shape) noisy_image[noise > 0.99] = 255 noisy_image[noise < 0.01] = 0 im[:,:,1] = median(noisy_image, disk(1)) noisy_image = img_as_ubyte(im2[:,:,2]) noise = np.random.random(noisy_image.shape) noisy_image[noise > 0.99] = 255 noisy_image[noise < 0.01] = 0 im[:,:,2] = median(noisy_image, disk(1)) # Load picture and detect edges image = img_as_ubyte(im[:,:,0]) edges = canny(image, sigma=3, low_threshold=30, high_threshold=85) # Detect two radii hough_radii = np.arange(3, 15, 1) hough_res = hough_circle(edges, hough_radii) # Select the most prominent 3 circles accums, cx, cy, radii = hough_circle_peaks(hough_res, hough_radii, total_num_peaks=3) #mean = np.mean(im[cy[:],cx[:],], axis=1) # Draw them #_id = ball(mean, accums) #if(_id != -1): #accums, center_x, center_y, radius = accums[_id], cx[_id], cy[_id], radii[_id] for center_y, center_x, radius, ac in zip(cy, cx, radii, accums): #accums, center_x, center_y, radius = accums[0], cx[0], cy[0], radii[0] image = color.gray2rgb(image) circy, circx = circle(center_y, center_x, radius, shape=image.shape) #image[circy, circx] = 255 image = im if(image[circy, circx, :].mean() > 160 and image[circy, circx, :].mean() < 180 and ac > 0.55 and np.std(image[circy, circx, :]) > 20 and np.std(image[circy, circx, :]) < 45 ): print(nome +' - accums: ' +str(round(ac,2)) + ' - mean: '+ str(round(image[circy, circx, :].mean(),2))) image[circy, circx] = 255 io.imsave('img_ball/'+nome, (image).astype('uint8')) #plt.imshow(image, cmap=plt.cm.gray) #plt.show() circy, circx = circle_perimeter(center_y, center_x, radius, shape=image.shape) return center_y, center_x return -1,-1
def generate_circles(im, circle_edges, greens, piece_size, CIRCLE_THRESHOLD, CIRCLE_GREEN_THRESHOLD): if im.shape[0] == im.shape[1] == 1: return [] # Find circles (othello pieces) print("Circle detection... ", end="", flush=True) radii_lim = np.arange(piece_size * 0.8, piece_size * 1.2) hough_res = hough_circle(circle_edges, radii_lim) prob, cx, cy, radii = hough_circle_peaks(hough_res, radii_lim, min_xdistance=int(piece_size), min_ydistance=int(piece_size), threshold=CIRCLE_THRESHOLD) circles = list(zip(prob, cx, cy, radii)) circles_not_intersecting = [] for i, circle in enumerate(circles): prob, x, y, rad = circle intersecting = False for (_, x_, y_, rad_) in circles[:i]: dist_sqrd = (x - x_)**2 + (y - y_)**2 if dist_sqrd < ((rad + rad_) / 2)**2: intersecting = True break if not intersecting: circles_not_intersecting.append(circle) circles_with_colors = [] for prob, x, y, rad in circles_not_intersecting: rad = int(rad) brightness_in_rad = [] green_in_rad = [] for x_ in range(-rad, rad): for y_ in range(-rad, rad): if (x_**2 + y_**2) < (rad - 3)**2: if 0 <= y + y_ < im.shape[0] and \ 0 <= x + x_ < im.shape[1]: brightness_in_rad.append(im[y + y_, x + x_].sum() / 3) green_in_rad.append(greens[y + y_, x + x_]) brightness_in_rad = np.array(brightness_in_rad) avg_green = sum(green_in_rad) / (len(green_in_rad) + 1) blacks = (brightness_in_rad < 0.6).sum() whites = (brightness_in_rad > 0.6).sum() if avg_green < CIRCLE_GREEN_THRESHOLD: circles_with_colors.append((prob, x, y, rad, blacks > whites / 2)) circles = circles_with_colors print("Done") return circles
def analyze(FileName): img = io.imread(FileName) xc, yc, t = img.data.shape grayscale = rgb2gray( img ) # To use the later image analyis, the initial image must be converted to grayscale image = img_as_ubyte( grayscale[0:xc, 0:yc] ) # converts the image to a specific file format that can later be analysed # the array after 'grayscale' holds the size of the image. edges = canny(image, sigma=3, low_threshold=max_radius * .1, high_threshold=max_radius * .2) # canny identifies any edges on the shape # sigma is required standard deviation, low and high threshold are the bounds for linking edges # It is recommended that you use 10% of the max possible cirlce size for the low_threshold and twice that for the high threshold h_radii = np.arange( min_radius, max_radius, 1 ) # The first two are used to identify the high and low end of radii to search for # This will need to be adjusted as different files are uploaded. hough_res = hough_circle( edges, h_radii ) # function that calculates a 3D array where a very similar circle can live. # It takes in the number of pixels that will be used to create the print("Analysis almost complete...") accums, x, y, radius = hough_circle_peaks( hough_res, h_radii, total_num_peaks=number_of_circles) # the hough_cirlce_peaks function takes the imaginary 'hough circle', the anticipated radii, and the anticiapted number of circles # it uses this to find the Peak values in 'hough space', the positions of the circles and the radii of the circles print("radius is:", radius) area = 3.1415926535897984626 * radius * radius return area print("area is: ", area) # Prints the radii of the identified circles fig, ax = alt.subplots(ncols=1, nrows=1, figsize=(10, 4)) image = color.gray2rgb(image) for center_y, center_x, radius in zip( y, x, radius ): # This for loop draws the circles that were generated earlier circy, circx = circle_perimeter(center_y, center_x, radius, shape=image.shape) image[circy, circx] = (220, 20, 20) ax.imshow(image) # This loads the edited image into the environment alt.show() # this takes the uploaded image and displays it for the user
def find_well_border(image, segmethod='bimodal', detmethod='region'): """ finds the border of the well to motivate future cropping around spots hough_radii are potential radii of the well in pixels this should be motivated based on magnification edge filter fit hough circle find the peak of the SINGULAR hough circle :param image: np.ndarray raw image, not inverted :param segmethod: str 'otsu' or 'hough' :return: center x, center y, radius of the one hough circle """ well_mask = thresh_and_binarize(image, method=segmethod, invert=False) # Now remove small objects. str_elem_size = 10 str_elem = disk(str_elem_size) well_mask = binary_opening(well_mask, str_elem) # well_mask = binary_fill_holes(well_mask) if detmethod == 'region': labels = measure.label(well_mask) props = measure.regionprops(labels) # let's assume ONE circle for now (take only props[0]) props = select_props(props, attribute="area", condition="greater_than", condition_value=10**5) props = select_props(props, attribute="eccentricity", condition="less_than", condition_value=0.5) well_mask[labels != props[0].label] = 0 cy, cx = props[ 0].centroid # notice that the coordinate order is different from hough. radii = int((props[0].minor_axis_length + props[0].major_axis_length) / 4 / np.sqrt(2)) # Otsu threshold fails occasionally and leads to asymmetric region. Averaging both axes makes the segmentation robust. # If above files, try bounding box. elif detmethod == 'hough': hough_radii = [300, 400, 500, 600] well_mask = thresh_and_binarize(image, method='bimodal') edges = canny(well_mask, sigma=3) hough_res = hough_circle(edges, hough_radii) aaccums, cx, cy, radii = hough_circle_peaks(hough_res, hough_radii, total_num_peaks=1) cx, cy = cx[0], cy[0] radii = radii[0] else: cx, cy, radii = None, None, None return [cy, cx], radii, well_mask
def dot_detection(img_gray, axis_x, axis_y): ## Mask img_height, img_weight = img_gray.shape down_bound = axis_x[0][1] left_bound = axis_y[0][0] background = np.max(img_gray) img = np.zeros_like(img_gray) pad_size = 0 img[:down_bound - pad_size, left_bound + pad_size:] = background - img_gray[:down_bound - pad_size, left_bound + pad_size:] thresh = threshold_otsu(img) img = img > thresh # [False or True] bool label_img, label_num = label(img, neighbors=None, background=None, return_num=True, connectivity=None) circle_radius = [] regions = regionprops(label_img, coordinates='xy') for region in regions: # remove warning in 0.14 vs 0.16 # take regions with large enough areas if region.bbox_area >= 20: circle_radius.append(region.equivalent_diameter//2) circle_r = max(set(circle_radius), key = circle_radius.count) print(' Most Radius: {}, and smallest radius: {}' .format(circle_r, sorted(circle_radius)[0])) label_centers = [] idx = 0 for region in regions: if abs(region.equivalent_diameter//2 - circle_r) > 1: label_patch = region.image label_patch = resize(label_patch, (label_patch.shape[0]*2, label_patch.shape[1]*2), anti_aliasing=True) # edge_sobel = sobel(label_patch) # thresh = threshold_otsu(edge_sobel) # edges = edge_sobel > thresh edges = canny(label_patch) hough_radii = np.asarray([circle_r * 2]) # np.arange(circle_r-1, circle_r+2) hough_res = hough_circle(edges, hough_radii) _, cx, cy, _ = hough_circle_peaks(hough_res, hough_radii, threshold=2/3 * np.max(hough_res)) min_r, min_c, max_r, max_c = region.bbox cx = list(map(lambda x: x/2+min_c, cx)) cy = list(map(lambda x: x/2+min_r, cy)) for centroid in zip(cy, cx): label_centers.append(centroid) else: label_centers.append(region.centroid) print('{} Circles detected'.format(len(label_centers))) # Draw them fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(10, 6)) image_label_overlay = label2rgb(label_img, image=img) for label_center in label_centers: center_y, center_x = label_center circy, circx = circle_perimeter(int(center_y), int(center_x), int(circle_r), shape=[int(img_height), int(img_weight)]) image_label_overlay[circy, circx] = (220, 20, 20) ax.set_title('Circle Detection') ax.imshow(image_label_overlay, cmap=plt.cm.gray) # plt.savefig('Circle_plot.png') plt.show() return label_centers
def IrisLocalization(eye): blured = cv2.bilateralFilter(eye, 9, 100, 100) Xp = blured.sum(axis=0).argmin() Yp = blured.sum(axis=1).argmin() x = blured[max(Yp - 60, 0):min(Yp + 60, 280), max(Xp - 60, 0):min(Xp + 60, 320)].sum(axis=0).argmin() y = blured[max(Yp - 60, 0):min(Yp + 60, 280), max(Xp - 60, 0):min(Xp + 60, 320)].sum(axis=1).argmin() Xp = max(Xp - 60, 0) + x Yp = max(Yp - 60, 0) + y if Xp >= 100 and Yp >= 80: blur = cv2.GaussianBlur(eye[Yp - 60:Yp + 60, Xp - 60:Xp + 60], (5, 5), 0) pupil_circles = cv2.HoughCircles(blur, cv2.HOUGH_GRADIENT, dp=1.2, minDist=200, param1=200, param2=12, minRadius=15, maxRadius=80) xp, yp, rp = np.round(pupil_circles[0][0]).astype("int") xp = Xp - 60 + xp yp = Yp - 60 + yp else: pupil_circles = cv2.HoughCircles(blured, cv2.HOUGH_GRADIENT, 4, 280, minRadius=25, maxRadius=55, param2=51) xp, yp, rp = np.round(pupil_circles[0][0]).astype("int") eye_copy = eye.copy() rp = rp + 7 # slightly enlarge the pupil radius makes a better result blured_copy = cv2.medianBlur(eye_copy, 11) blured_copy = cv2.medianBlur(blured_copy, 11) blured_copy = cv2.medianBlur(blured_copy, 11) eye_edges = cv2.Canny(blured_copy, threshold1=15, threshold2=30, L2gradient=True) eye_edges[:, xp - rp - 30:xp + rp + 30] = 0 hough_radii = np.arange(rp + 45, 150, 2) hough_res = hough_circle(eye_edges, hough_radii) accums, xi, yi, ri = hough_circle_peaks(hough_res, hough_radii, total_num_peaks=1) iris = [] iris.extend(xi) iris.extend(yi) iris.extend(ri) if ((iris[0] - xp)**2 + (iris[1] - yp)**2)**0.5 > rp * 0.3: iris[0] = xp iris[1] = yp return np.array(iris), np.array([xp, yp, rp])
def _get_center(image): gray = rgb2gray(image) edges = canny(gray, sigma=0) hough_radii = np.arange(180, 240, 20) hough_res = hough_circle(edges, hough_radii) accums, cx, cy, radii = hough_circle_peaks(hough_res, hough_radii, total_num_peaks=1) return cx[0], cy[0]
def punchhole_removal(im): import numpy as np from PIL import Image from skimage import io from skimage.color import rgba2rgb, rgb2gray from skimage.transform import hough_circle, hough_circle_peaks from skimage.feature import canny from skimage.draw import circle from skimage.util import img_as_ubyte ''' check for punch holes and remove ''' max_peaks = 24 #maximum number of peaks to be found. changed from 99 to 24 for reducing the unnecessary punch holes being filled. img = np.array(im)# Load picture . img_rgb = rgba2rgb(img)# convert to RGB img_gray = rgb2gray(img_rgb)# convert to gray image = img_as_ubyte(img_gray) width, height = image.shape x1 = punchhole_margin x2 = (int)(width - punchhole_margin) y1 = (int)(height - punchhole_margin) y2 = punchhole_margin edges = canny(image, 3, 10, 40) # perform canny to detect the edges hough_radii = np.arange(31, 34, 1) #get the radius range with step as 1. hough_res = hough_circle(edges, hough_radii) # detect the circles centres coordinates # Select the most prominent circles based on the max_peaks accums, cx, cy, radii = hough_circle_peaks(hough_res, hough_radii,total_num_peaks=max_peaks) for center_y, center_x, radius in zip(cy, cx, radii): #if the circles centres fall in the border regions, #get the dominant color near the hole and fill the hole with a linear gradient of the dominant color if(((0 < center_y < width) and (0 < center_x < y2)) or \ ((0 < center_y < width) and (y1 < center_x < height)) or\ ((0 < center_y < x1) and (0 < center_x < height)) or \ ((x2 < center_y < width) and (0 < center_x < height))): index=0 rr, cc= circle(center_y, center_x, radius+1, img.shape) dominantpix = dominantcolor(center_x, center_y, radius, img) dark_grad = [dominantpix[0], dominantpix[1],dominantpix[2]] light_grad = [dominantpix[0]+1, dominantpix[1]+1, dominantpix[2]+1] #white_grad = [255,255,255] RGBA_list = lineargradient(dark_grad,light_grad,len(list(rr))) for i , j in zip(list(rr), list(cc)): pixlist = RGBA_list[index] pixtuple = tuple(pixlist) img[i,j]= (pixtuple[0], pixtuple[1], pixtuple[2], 255) index += 1 finalimage=Image.fromarray(img) return finalimage
def find_circles(image, count_): image = 255 - image image[np.where(image > 170)] = 255. image = np.array(image, dtype='float64') prev_proc = sum(sum(image)) / (image.shape[0] * image.shape[1]) / 255. # 0.17, 0.031 are constants based on example 'many_circles.bmp' if count_ == -1: bord1 = 0.17 * prev_proc bord2 = 0.031 * prev_proc else: bord1 = -10000 bord2 = -10000 final_list_of_circles = [] max_amount_of_circles = 18 if count_ != -1: max_amount_of_circles = int(count_) for indd in range(max_amount_of_circles): edges = canny(image, sigma=3, low_threshold=10, high_threshold=50) minim_radii = int(min(image.shape[0], image.shape[1]) / 20) maxim_radii = int(min(image.shape[0], image.shape[1]) / 2) # Adapt step in Hough transform if picture is too big stepp = 1 if (maxim_radii - minim_radii) > 200: stepp = 2 if (maxim_radii - minim_radii) > 400: stepp = 4 hough_radii = np.arange(minim_radii, maxim_radii, stepp) hough_res = hough_circle(edges, hough_radii) accums, cx, cy, radii = hough_circle_peaks(hough_res, hough_radii, total_num_peaks=1) fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(10, 4)) image1 = np.zeros((image.shape[0], image.shape[1])) for center_y, center_x, radius in zip(cy, cx, radii): circy, circx = circle_perimeter(center_y, center_x, radius) for ccy, ccx in zip(circy, circx): if 0 < ccy < image.shape[0] and 0 < ccx < image.shape[1]: image1[ccy][ccx] = 255 # Thick segments before subtracting selem = disk(5) thickimage1 = binary_dilation(image1, selem) thickimage1 = np.uint8(thickimage1) * 255 image = subtract_skimage(image, thickimage1) white_proc = sum(sum(image)) / (image.shape[0] * image.shape[1]) / 255 # if prev iteration is very similar to new iteration, stop if abs(white_proc - prev_proc) < 0.3 * bord2 + 0.7 * 0.0009: break for center_y, center_x, radius in zip(cy, cx, radii): final_list_of_circles.append( Circle(Point(center_y, center_x), radius)) prev_proc = white_proc # if procent of white pixels is too small, stop if white_proc < 0.3 * bord1 + 0.7 * 0.005: break #ax.imshow(image, cmap=plt.cm.gray) #plt.show() return final_list_of_circles
def detObj(image): edges = canny(image, sigma=2, low_threshold=10, high_threshold=20) #io.imsave("edges.bmp", edges) hough_radii = [16] hough_res = hough_circle(edges, hough_radii) accums, cx, cy, r = hough_circle_peaks(hough_res, hough_radii, total_num_peaks=1) return cx, cy, r
def punchhole_removal(im): import numpy as np from PIL import Image from skimage import io from skimage.color import rgba2rgb, rgb2gray from skimage.transform import hough_circle, hough_circle_peaks from skimage.feature import canny from skimage.draw import circle from skimage.util import img_as_ubyte ''' check for punch holes and remove ''' max_peaks = 99#maximum number of peaks to be found. img = np.array(im)# Load picture . img_rgb = rgba2rgb(img)# convert to RGB img_gray = rgb2gray(img_rgb)# convert to gray image = img_as_ubyte(img_gray) width, height = image.shape x1 = (int)(width * 8//100) x2 = (int)(width - (width * 8//100)) y1 = (int)(height - (height * 8//100)) y2 = (int)(height * 8//100) edges = canny(image, 3, 10, 40) # perform canny to detect the edges hough_radii = np.arange(31, 34, 1) #get the radius range with step as 1. hough_res = hough_circle(edges, hough_radii) # detect the circles centres coordinates # Select the most prominent circles based on the max_peaks accums, cx, cy, radii = hough_circle_peaks(hough_res, hough_radii,total_num_peaks=max_peaks) for center_y, center_x, radius in zip(cy, cx, radii): #if the circles centres fall in the border regions, #get the dominant color near the hole and fill the hole with a linear gradient of the dominant color if(((0 < center_y < width) and (0 < center_x < y2)) or \ ((0 < center_y < width) and (y1 < center_x < height)) or\ ((0 < center_y < x1) and (0 < center_x < height)) or \ ((x2 < center_y < width) and (0 < center_x < height))): index=0 rr, cc= circle(center_y, center_x, radius+1, img.shape) dominantpix = dominantcolor(center_x, center_y, radius, img) dark_grad = [dominantpix[0], dominantpix[1],dominantpix[2]] light_grad = [dominantpix[0]+1, dominantpix[1]+1, dominantpix[2]+1] #white_grad = [255,255,255] RGBA_list = lineargradient(dark_grad,light_grad,len(list(rr))) for i , j in zip(list(rr), list(cc)): pixlist = RGBA_list[index] pixtuple = tuple(pixlist) img[i,j]= (pixtuple[0], pixtuple[1], pixtuple[2], 255) index += 1 finalimage=Image.fromarray(img) return finalimage
def get(self, actions=None, res_segs=None): import timeit import matplotlib.pyplot as plt start = timeit.timeit() edge_reward_g = torch.ones(res_segs.shape[0]) edge_reward_l = torch.zeros_like(actions) for g_idx, res_seg in enumerate(res_segs): edges = self.env.b_edge_ids[:, self.env.e_offs[g_idx]:self.env.e_offs[g_idx+1]] - self.env.n_offs[g_idx] segmentation = (res_seg / res_seg.max()) obj_lbls = torch.unique(segmentation) masses = torch.zeros(obj_lbls.size(), dtype=torch.float) # centers_of_mass = np.zeros(obj_lbls.size() + (2, ), dtype=np.float) involved_bad_sp = [] if len(obj_lbls) < self.range_num[0] - 1: edge_reward_g[g_idx] = - (self.range_num[0] - 1) / len(obj_lbls) continue elif len(obj_lbls) > self.range_num[1] + 1: edge_reward_g[g_idx] = - len(obj_lbls) / (self.range_num[1] + 1) continue edge_image = ((- self.max_p(-segmentation.unsqueeze(0)).squeeze()) != segmentation).float().cpu().numpy() hough_radii = np.arange(self.range_rad[0], self.range_rad[1]) - 1 # account for min filter (inner circle edge) hough_res = hough_circle(edge_image, hough_radii) accums, cx, cy, radii = hough_circle_peaks(hough_res, hough_radii, total_num_peaks=self.range_num[1]) mp_circles = torch.from_numpy(np.stack([cx, cy], axis=1)) accepted_circles = (cx > (self.range_rad[1] - 1)) & (cx < segmentation.shape[0] - (self.range_rad[1] - 1)) & \ (cy > (self.range_rad[1] - 1)) & (cy < segmentation.shape[1] - (self.range_rad[1] - 1)) if any(accepted_circles): mp_circles = mp_circles[accepted_circles] sample_r = torch.randint(self.range_rad[0] // 2, self.range_rad[1] - 1, (self.n_samples,)) points = self.angle_scals * sample_r.unsqueeze(1).float() sample_points = (points.unsqueeze(0) + mp_circles.float().unsqueeze(1)).long() assert all(sample_points.view(-1) >= 0) and all(sample_points.view(-1) < self.env.init_sp_seg.shape[1]) circle_sp = self.env.init_sp_seg[g_idx, sample_points[..., 0], sample_points[..., 1]] mask_circle_sp = (edges.float().unsqueeze(-1).unsqueeze(-1) == circle_sp.unsqueeze(0).unsqueeze(0)).sum(-1) >= 1 mask_circle_sps = mask_circle_sp[0] | mask_circle_sp[1] for mask_circle_sp, val in zip(mask_circle_sps.T, accums): circle_edges = torch.nonzero(mask_circle_sp).squeeze() + self.env.e_offs[g_idx] edge_reward_l[circle_edges] += val * 10 reward_l = edge_reward_l[self.env.b_subgraph_indices].view(-1, self.env.cfg.gen.s_subgraph).sum(-1) end = timeit.timeit() time = start - end return reward_l.to(actions.device), edge_reward_g.to(actions.device)
def get_image_circles( image: ndarray, circle_radius: float, circle_count: int = -1, search_radius: float = 0) -> List[Tuple[Tuple[float, float], float]]: """ Get circular parts of an image matching the size criteria :param image: a greyscale image as a numpy array :param circle_radius: a circle radius to search for, in pixels :param circle_count: the number of expected circles in the image :param search_radius: an additional area around the expected circle size to search :returns: a list of center co-ordinate tuples and radii """ from numpy import inf from skimage.transform import hough_circle, hough_circle_peaks from skimage.feature import canny from skimage.filters import threshold_otsu if circle_count == -1: circle_count = inf if image.size == 0: raise ValueError("The supplied image cannot be empty") img = image.copy() # Find edges in the image threshold = threshold_otsu(img) edges = canny(img < threshold, sigma=3) # Check 2 * search_radius pixels around the target radius, in steps of 10 radii = range(circle_radius - search_radius, circle_radius + search_radius, 10) hough_circles = hough_circle(edges, radii) # Find the most significant circles _, cx, cy, radii = hough_circle_peaks(hough_circles, radii, min_xdistance=circle_radius, min_ydistance=circle_radius, total_num_peaks=circle_count) # Create a Dict with y values as keys and row numbers as values # Allows a quick lookup of the row values for sorting row_groups = dict() row_count = 0 for i, x in enumerate(sorted(cy)): if i == 0 or abs((sorted(cy)[i - 1]) - x) > circle_radius: row_count += 1 row_groups[x] = row_count # Group and order coordinates in rows from top left coordinates = sorted(zip(cy, cx), key=lambda k: (row_groups[k[0]], 0, k[1])) radii = [max(radii, key=radii.tolist().count) for x in radii] return [*zip(coordinates, radii)]
def pupil_segmentation_hough(self, image): # Fornece uma gama de raios plausíveis hough_radii = np.arange(40, 80, 2) hough_res = hough_circle(image, hough_radii) _, cols, rows, rads = hough_circle_peaks(hough_res, hough_radii, total_num_peaks=1) # Seleciona a região com maior raio encontrado region = max(zip(rows, cols, rads), key=lambda item: item[2]) return region
def test_hough_circle_peaks_total_peak(): img = np.zeros((120, 100), dtype=int) x_0, y_0, rad_0 = (99, 50, 20) y, x = circle_perimeter(y_0, x_0, rad_0) img[x, y] = 1 x_1, y_1, rad_1 = (49, 60, 30) y, x = circle_perimeter(y_1, x_1, rad_1) img[x, y] = 1 radii = [rad_0, rad_1] hspaces = tf.hough_circle(img, radii) out = tf.hough_circle_peaks(hspaces, radii, min_xdistance=1, min_ydistance=1, threshold=None, num_peaks=np.inf, total_num_peaks=1) assert_equal(out[1][0], np.array([y_1,])) assert_equal(out[2][0], np.array([x_1,])) assert_equal(out[3][0], np.array([rad_1,]))
from skimage.feature import canny from skimage.draw import circle_perimeter from skimage.util import img_as_ubyte # Load picture and detect edges image = img_as_ubyte(data.coins()[160:230, 70:270]) edges = canny(image, sigma=3, low_threshold=10, high_threshold=50) # Detect two radii hough_radii = np.arange(20, 35, 2) hough_res = hough_circle(edges, hough_radii) # Select the most prominent 5 circles accums, cx, cy, radii = hough_circle_peaks(hough_res, hough_radii, total_num_peaks=3) # Draw them fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(10, 4)) image = color.gray2rgb(image) for center_y, center_x, radius in zip(cy, cx, radii): circy, circx = circle_perimeter(center_y, center_x, radius) image[circy, circx] = (220, 20, 20) ax.imshow(image, cmap=plt.cm.gray) plt.show() ###################################################################### # Ellipse detection # =================