def pickPolygons(self, region_names, bands=0): """ Creates a matplotlib gui for selecting polygon regions in an image. *Arguments*: - image = the image to pick on - names = a list containing the names of the regions to pick. If a string is passed only one name is used. - bands = the bands of the image to plot. """ if isinstance(region_names, str): region_names = [region_names] assert isinstance(region_names, list), "Error - names must be a list or a string." # set matplotlib backend backend = matplotlib.get_backend() matplotlib.use('Qt5Agg') # need this backend for ROIPoly to work # plot image and extract roi's fig, ax = self.quick_plot(bands) roi = MultiRoi(roi_names=region_names) plt.close(fig) # close figure # extract regions regions = [] for name, r in roi.rois.items(): # store region x = r.x y = r.y regions.append(np.vstack([x, y]).T) # restore matplotlib backend (if possible) try: matplotlib.use(backend) except: print( "Warning: could not reset matplotlib backend. Plots will remain interactive..." ) pass return regions
def capture_polygons(image_file_name, instruction_string=''): """This interactiv method allows you to draw polygons and captures vertices. N = number of polygons drawn :param image_file_name: Path to image file. This method will display the image in a figure window and allow you to draw polygons on top. :param instruction_string: String with instructions for the user. :return: polygon_objects_pixel_coords: length-N list of polygons (instances of `shapely.geometry.Polygon`), each containing vertices in pixel coordinates. :return: num_pixel_rows: Number of pixel rows in the image. :return: num_pixel_columns: Number of pixel columns in the image. """ error_checking.assert_file_exists(image_file_name) error_checking.assert_is_string(instruction_string) image_matrix = Image.open(image_file_name) num_pixel_columns, num_pixel_rows = image_matrix.size pyplot.imshow(image_matrix) pyplot.title(instruction_string) pyplot.show(block=False) multi_roi_object = MultiRoi() string_keys = list(multi_roi_object.rois.keys()) integer_keys = numpy.array([int(k) for k in string_keys], dtype=int) sort_indices = numpy.argsort(integer_keys) integer_keys = integer_keys[sort_indices] string_keys = [string_keys[k] for k in sort_indices] num_polygons = len(integer_keys) polygon_objects_pixel_coords = [] for i in range(num_polygons): this_roi_object = multi_roi_object.rois[string_keys[i]] these_x_coords = numpy.array([this_roi_object.x[0]] + list(reversed(this_roi_object.x))) if len(these_x_coords) < 4: warning_string = ( 'Found polygon with only {0:d} points. A valid polygon must ' 'have at least 3 points. Skipping this polygon.' ).format(len(these_x_coords) - 1) warnings.warn(warning_string) continue these_y_coords = numpy.array([this_roi_object.y[0]] + list(reversed(this_roi_object.y))) this_polygon_object = polygons.vertex_arrays_to_polygon( x_coordinates=these_x_coords, y_coordinates=these_y_coords) polygon_objects_pixel_coords.append(this_polygon_object) return polygon_objects_pixel_coords, num_pixel_rows, num_pixel_columns
import trackpy as tp # noqa: E402 from roipoly import MultiRoi # noqa: E402 frames = pims.ImageSequence("../test/k255e_pos3_mag_tif_invert/*.tif", as_grey=True) # print(frames[0]) # first frame img = frames[0] fig = plt.figure() plt.imshow(img, interpolation='nearest', cmap="Greys") plt.title("Click on the button to add a new ROI") # Draw multiple ROIs multiroi_unnamed = MultiRoi() # Draw all ROIs plt.imshow(img, interpolation='nearest', cmap="Greys") roi_names = [] for name, roi in multiroi_unnamed.rois.items(): roi.display_roi() # roi.display_mean(img) roi_names.append(name) plt.legend(roi_names, bbox_to_anchor=(1.2, 1.05)) plt.show() # Show ROI masks for name, roi in multiroi_unnamed.rois.items(): # TODO just multiply mask with image in each iteration?
return answer == 'y' for color, roi_color in COLORS: is_ok = False if not prompt_is_ok(f"Do you want to label color {color}? [y/n]: "): color_pixels[color] = np.array([]) continue while not is_ok: print(f"Labeling color {color} ...") fig = plt.figure() plt.imshow(img, interpolation='nearest', cmap="Greys") plt.title(f"Add ROI for Color:{color}") multiroi = MultiRoi(color_cycle=(roi_color, )) tmask = np.zeros(img.shape[:-1]) for name, roi in multiroi.rois.items(): mask = roi.get_mask(cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)) tmask += mask masked_img = img.copy() masked_img[tmask == 0, :] = 0 plt.imshow(masked_img) plt.show() is_ok = prompt_is_ok(f"Is color {color} labeled correctly? [y/n]: ") if not is_ok: print(f"Please label color {color} again.") else: rois.extend(multiroi.rois.values())
import numpy as np from matplotlib import pyplot as plt from roipoly import MultiRoi logging.basicConfig(format='%(levelname)s ''%(processName)-10s : %(asctime)s ' '%(module)s.%(funcName)s:%(lineno)s %(message)s', level=logging.INFO) # Create image img = np.ones((100, 100)) * range(0, 100) # Show the image fig = plt.figure() plt.imshow(img, interpolation='nearest', cmap="Greys") plt.title("Click on the button to add a new ROI") # Draw multiple ROIs multiroi_named = MultiRoi(roi_names=['My first ROI', 'My second ROI']) # Draw all ROIs plt.imshow(img, interpolation='nearest', cmap="Greys") roi_names = [] for name, roi in multiroi_named.rois.items(): roi.display_roi() roi.display_mean(img) roi_names.append(name) plt.legend(roi_names, bbox_to_anchor=(1.2, 1.05)) plt.show()
def grab_image_segment(num_img=5): ''' Grabs a part of the image which has red sign for labelling and annotating and saves the output as a numpy array ''' #path = '/home/aditya/Documents/Course_Work/sensing_and_estimation/HW_1/ECE276A_PR1/hw1_starter_code/best_images/' ## New Path ## path = '/home/aditya/Documents/Course_Work/sensing_and_estimation/HW_1/ECE276A_PR1/hw1_starter_code/image_for_label/' image_path_list = [] for r, d, f in os.walk(path): for file in f: if '.jpg' in file: image_path_list.append(os.path.join(r, file)) print(image_path_list) for image in range(len(image_path_list)): if (image > 89): #img = mpimg.imread('/home/aditya/Documents/Course_Work/sensing_and_estimation/HW_1/ECE276A_PR1/hw1_starter_code/trainset/' + str(image) + '.jpg') img = mpimg.imread(image_path_list[image]) #display the image for marking regions fig = plt.figure(1) plt.imshow(img) plt.show(block=False) #roi = RoiPoly(color='red',fig=fig) roi = MultiRoi(fig=fig) #plt.imshow(roi.get_mask(img))#,interpolation='nearest',cmap='Greys') img_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) mask = None for msk in roi.rois.keys(): mask = roi.rois[msk].get_mask( img_grey) if mask is None else np.logical_or( mask, roi.rois[msk].get_mask(img_grey)) #mask = roi.get_mask(img_grey) mask_np = 1 * mask mask_complement = 1 * np.logical_not(mask_np) img_masked = np.zeros(img.shape) img_comp_masked = np.zeros(img.shape) mask_shape = sum(sum(mask_np)) mask_complement_shape = img.shape[0] * img.shape[1] - mask_shape img_masked = np.zeros((mask_shape, 3)) img_comp_masked = np.zeros((mask_complement_shape, 3)) mask_cntr, mask_complement_cntr = 0, 0 for i in range(img.shape[0]): for j in range(img.shape[1]): if (mask[i, j]): #Area of interest img_masked[mask_cntr, :] = img[i, j, :] mask_cntr += 1 else: img_comp_masked[mask_complement_cntr, :] = img[i, j, :] mask_complement_cntr += 1 #plt.imshow(mask_np,cmap='gray') #plt.show() print("Red Data is {} Non Red Data is {}".format( mask_cntr, mask_complement_cntr)) print(image) ## Old Data Path ## #np.save('best_cln/image_masked_'+str(image),img_masked) #np.save('best_cln/image_masked_complement_'+str(image),img_comp_masked) np.save('labeled_images/red/red_' + str(image), img_masked) np.save('labeled_images/non_red/non_red_' + str(image), img_comp_masked)
# inplace=True) # immobile_beads_pos.rename(columns={'1frame_delta_y': 'avg_1frame_delta_y'}, # inplace=True) # immobile_beads_pos.to_csv(results_path + "immobile_beads.csv") # print(immobile_beads_pos.head()) # print(all_beads_masked.shape) # print(all_beads_masked) # plt.imshow(all_beads_masked[-1]) # plt.show() # Select cell ROIs fig = plt.figure() plt.imshow(frames[-1]) plt.title("Select cell boundaries") cell_rois = MultiRoi() # This instance stores all ROIs # Draw all ROIs to confirm plt.imshow(frames[-1]) roi_names = [] for name, roi in cell_rois.rois.items(): roi.display_roi() roi_names.append("cell" + name) plt.legend(roi_names, bbox_to_anchor=(1.2, 1.05)) plt.savefig(results_path + 'cell_ROIs.svg') plt.show() cells_bead_pos = pd.DataFrame() # Mask cells for name, roi in cell_rois.rois.items():
return answer == 'y' for color, roi_color in COLORS: is_ok = False if not prompt_is_ok(f'Do you want to label color {color}? [y/n]: '): color_pixels[color] = np.array([]) continue while not is_ok: print(f'Labeling color {color} ...') fig = plt.figure() plt.imshow(img, interpolation='nearest', cmap='Greys') plt.title(f'Add ROI for Color:{color}') multiroi = MultiRoi(color_cycle=(roi_color, )) tmask = np.zeros(img.shape[:-1]) for name, roi in multiroi.rois.items(): mask = roi.get_mask(cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)) tmask += mask masked_img = img.copy() masked_img[tmask == 0, :] = 0 plt.imshow(masked_img) plt.show() is_ok = prompt_is_ok(f'Is color {color} labeled correctly? [y/n]: ') if not is_ok: print(f'Please label color {color} again.') else: rois.extend(multiroi.rois.values())
def grab_image_segment(num_img=5): ''' Grabs a part of the image which has red sign for labelling and annotating and saves the output as a numpy array ''' path = '/home/aditya/Documents/Course_Work/sensing_and_estimation/HW_1/ECE276A_PR1/hw1_starter_code/trainset/' image_path_list = [] for r, d, f in os.walk(path): for file in f: if '.jpg' in file: image_path_list.append(os.path.join(r, file)) for image in range(num_img): #img = mpimg.imread('/home/aditya/Documents/Course_Work/sensing_and_estimation/HW_1/ECE276A_PR1/hw1_starter_code/trainset/' + str(image) + '.jpg') img = mpimg.imread(image_path_list[image]) #display the image for marking regions fig = plt.figure(1) plt.imshow(img) plt.show(block=False) #roi = RoiPoly(color='red',fig=fig) roi = MultiRoi(fig=fig) #plt.imshow(roi.get_mask(img))#,interpolation='nearest',cmap='Greys') img_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) mask = None for msk in roi.rois.keys(): mask = roi.rois[msk].get_mask( img_grey) if mask is None else np.logical_or( mask, roi.rois[msk].get_mask(img_grey)) #mask = roi.get_mask(img_grey) mask_np = 1 * mask mask_complement = np.logical_not(mask_np) #img_masked = np.zeros(img.shape) #img_comp_masked = np.zeros(img.shape) mask_shape = sum(sum(mask_np)) mask_complement_shape = img.shape[0] * img.shape[1] - mask_shape img_masked = np.zeros((mask_shape, 3)) img_comp_masked = np.zeros((mask_complement_shape, 3)) mask_cntr, mask_complement_cntr = 0, 0 for i in range(img.shape[0]): for j in range(img.shape[1]): if (mask[i, j]): #Area of interest img_masked[mask_cntr, :] = img[i, j, :] mask_cntr += 1 else: img_comp_masked[mask_complement_cntr, :] = img[i, j, :] mask_complement_cntr += 1 #img_masked[:,:,0] = img[:,:,0] * mask_np #img_masked[:,:,1] = img[:,:,1] * mask_np #img_masked[:,:,2] = img[:,:,2] * mask_np #img_comp_masked[:,:,0] = img[:,:,0] * mask_complement #img_comp_masked[:,:,1] = img[:,:,1] * mask_complement #img_comp_masked[:,:,2] = img[:,:,2] * mask_complement plt.imshow(mask_np, cmap='gray') plt.show() red_ftr = np.zeros((mask_cntr, 10)) for data in range(mask_cntr): red_ftr[data, 0] = 1 red_ftr[data, 1] = img_masked[data, 0]**2 red_ftr[data, 2] = img_masked[data, 1]**2 red_ftr[data, 3] = img_masked[data, 2]**2 red_ftr[data, 4] = img_masked[data, 0] * img_masked[data, 2] red_ftr[data, 5] = img_masked[data, 1] * img_masked[data, 2] red_ftr[data, 6] = img_masked[data, 1] * img_masked[data, 0] red_ftr[data, 7] = img_masked[data, 0] red_ftr[data, 8] = img_masked[data, 1] red_ftr[data, 9] = img_masked[data, 2] non_red_ftr = np.zeros((mask_complement_cntr, 10)) for data in range(mask_complement_cntr): non_red_ftr[data, 0] = 1 non_red_ftr[data, 1] = img_comp_masked[data, 0]**2 non_red_ftr[data, 2] = img_comp_masked[data, 1]**2 non_red_ftr[data, 3] = img_comp_masked[data, 2]**2 non_red_ftr[data, 4] = img_comp_masked[data, 0] * img_comp_masked[data, 2] non_red_ftr[data, 5] = img_comp_masked[data, 1] * img_comp_masked[data, 2] non_red_ftr[data, 6] = img_comp_masked[data, 1] * img_comp_masked[data, 0] non_red_ftr[data, 7] = img_comp_masked[data, 0] non_red_ftr[data, 8] = img_comp_masked[data, 1] non_red_ftr[data, 9] = img_comp_masked[data, 2] print("Red Data is {} Non Red Data is {}".format( mask_cntr, mask_complement_cntr)) np.save('image_masked_' + str(image), red_ftr) np.save('image_masked_complement_' + str(image), non_red_ftr)