def draw_mask(frame):
    plt.imshow(frame, cmap='gray', vmin=0, vmax=200)
    mask_left = RoiPoly(color='r')
    plt.imshow(frame, cmap='gray', vmin=0, vmax=200)
    mask_right = RoiPoly(color='b')

    mask = numpy.logical_or(mask_left.get_mask(frame),
                            mask_right.get_mask(frame))
    return mask
Exemplo n.º 2
0
def roi1():
    roi1_properties = {'x': [1, 1, 3, 3], 'y': [1, 3, 3, 1]}
    fig = plt.figure()
    roi1 = RoiPoly(color='r', fig=fig, show_fig=False)
    roi1.x = roi1_properties['x']
    roi1.y = roi1_properties['y']
    return roi1
Exemplo n.º 3
0
def label():
    if len(sys.argv)>=2:
        color = sys.argv[1]
    else:
        print('color?')
        color = input()
    ni = ''
    
    data = np.array([0,0,0])

    while(not ni == 'q'):
        print("input image number:")
        ni = input()
        if ni =='q':
            break
        else:
            fig = plt.figure()
            img = cv2.imread('trainset/'+ni+'.png')
            plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB),interpolation='nearest')
            roi = RoiPoly(color='r',fig=fig)
            mask = roi.get_mask(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY))
            data = np.vstack((data,handle(img,mask))) # Stack data sample
            data = np.array(list(filter(lambda x: (x>=1).any(),data)))
            print(str(data.shape))
            print("label next press ENTER, finish label press Q then ENTER")
            ni = input()
        np.save(color+'.npy',data)
def label_barrels(img):
    '''
    Generates a mask for the barrel
    '''

    
    fig = set_fig(img, 'label barrels')
    # Let user draw first ROI to mark red barrell
    roi_barrel = RoiPoly(color='r', fig=fig)
    mask_barrel = roi_barrel.get_mask(img[:, :, 0])
    print(mask_barrel.shape)
    # plt.imshow(mask_barrel)
    

    # truncated = len(img[:, :, 0].flatten())
    # x_indices = np.concatenate((img[:, :, 0].flatten().reshape(truncated,1), img[:, :, 1].flatten().reshape(truncated,1)), axis=1)
    # x_new = np.concatenate((x_indices, img[:, :, 2].flatten().reshape(truncated,1)), axis=1)
    # x_barrel = x_new[mask_barrel.flatten()]
    # x_notbarrel = x_new[np.invert(mask_barrel).flatten()]

    
    print(sum(mask_barrel.flatten()))
    # print(sum(np.invert(mask_barrel).flatten()))

    return mask_barrel
Exemplo n.º 5
0
def custom_mask(img):
    """
    Image segmentation function to create a custom polygon mask, and evalute radius and position of the masked object.
    Need to use %matplotlib qt in jupyter notebook
    Args:
        img(array): Grayscale image as a Numpy array
    Returns:
        dict: Dictionary with keys: mask, radius, centroid (x/y)
    """
    height = img.shape[0]
    width  = img.shape[1]
    # click polygon mask interactive
    plt.ion()
    plt.imshow(img, extent=[0, width, height, 0])
    plt.text(0.5, 1.05,'Click Polygon Mask with left click, finish with right click',  fontsize=12,
         horizontalalignment='center',
         verticalalignment='center',c='darkred', transform= plt.gca().transAxes)#     transform = ax.transAxes)
    my_roi = RoiPoly(color='r')
    # Extract mask and segementation details
    mask = np.flipud(my_roi.get_mask(img))   # flip mask due to imshow 
    # determine radius of spheroid
    radius = np.sqrt(np.sum(mask) / np.pi)
    # determine center of mass
    cy, cx = scipy_meas.center_of_mass(mask)
    # hide pop-up windows   
    plt.ioff()
    # return dictionary containing spheroid information
    return {'mask': mask, 'radius': radius, 'centroid': (cx, cy)} 
def annotate(img):
    '''
	   Create a polygon for binary masking 
	   Call the funciton after plt.imshow(your_image)
	'''

    my_roi = RoiPoly(color='r')
    mask = my_roi.get_mask(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY))
    return mask
Exemplo n.º 7
0
def manually_roi_select(lista_img, mask_list, n_mask):
    fig = plt.figure()
    plt.imshow(lista_img[int(n_mask)-1], interpolation='nearest', cmap=plt.cm.gray)
    plt.colorbar()
    plt.title("left click: line segment right click or double click: close region")
    roi1 = RoiPoly(color='r', fig=fig)
    mask = roi1.get_mask(mask_list[int(n_mask)-1])
    mask_list[int(n_mask)-1] = mask
    return roi1, mask
Exemplo n.º 8
0
def draw_roi(frames, region):
    plt.imshow(frames[5000], cmap='gray', vmin=0, vmax=255)
    plt.title("Draw " + region + " ROI")
    roi = RoiPoly(color='r')
    mask = roi.get_mask(frames[0])

    gradient_signal = np.abs(np.gradient(np.mean(frames[:, mask], axis=1)))
    threshold = np.mean(gradient_signal) + np.std(gradient_signal)

    return gradient_signal, threshold
Exemplo n.º 9
0
 def manual_crop(s, normalize, n_slice):
     fig = plt.figure(figsize=(15, 8))
     plt.imshow(s,
                interpolation="nearest",
                cmap=plt.cm.gray,
                norm=normalize)
     plt.colorbar()
     plt.title(f"Slice: {n_slice}")
     plt.show(block=False)
     roi1 = RoiPoly(color='r', fig=fig)
     plt.close(fig)
     mask = roi1.get_mask(s)
     return s * mask
Exemplo n.º 10
0
 def setUp(self):
     roi1_properties = {'x': [1, 1, 3, 3], 'y': [1, 3, 3, 1]}
     fig = plt.figure()
     roi1 = RoiPoly(color='r', fig=fig, show_fig=False)
     roi1.x = roi1_properties['x']
     roi1.y = roi1_properties['y']
     self.roi1 = roi1
     self.img1 = np.ones((5, 5)) * range(5)
     self.roi1_expected_mask = np.array(
         [[False, False, False, False, False],
          [False, False, False, False, False],
          [False, True, True, True, False],
          [False, True, True, True, False],
          [False, False, False, False, False]])
def roicrop(img):

    # Show the image
    fig = plt.figure()

    plt.imshow(img, interpolation='nearest', cmap="Greys")
    plt.title("left click: line segment         right click: next figure")
    plt.show(block=False)

    # Let user draw first ROI
    roi = RoiPoly(color='r', fig=fig)

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    mask = roi.get_mask(gray)
    return roi, mask
Exemplo n.º 12
0
def gate_cells(df, x_name, y_name):
    import numpy as np
    import matplotlib.path as mplPath
    import matplotlib.pyplot as plt
    from roipoly import RoiPoly
    """∑
    Gate cells
    
    """
    plt.figure()
    sb.scatterplot(data=df, x=x_name, y=y_name)
    gate = RoiPoly(color='r')  # Draw polygon gate
    gate_p = mplPath.Path(np.vstack((gate.x, gate.y)).T)
    gateI = gate_p.contains_points(np.vstack((df[x_name], df[y_name])).T)
    return df[gateI]
Exemplo n.º 13
0
def label_image(img_path, img_id):
    # Create image
    img = Image.open('trainset/{}.jpg'.format(img_id))

    # Show the image
    fig = plt.figure()
    plt.imshow(img)

    # Let user draw first ROI
    roi = RoiPoly(color='r', fig=fig)
    mask = roi.get_mask(np.array(img)[:, :, 0])
    plt.imshow(mask)
    plt.show()
    print(mask)
    np.save('dataset/masks/{}.npy'.format(img_id), mask)
    img.save('dataset/imgs/{}.png'.format(img_id))
Exemplo n.º 14
0
 def draw_roi(self):
     """
     This function is meant to "test drive" the roipoly interface since it is new to the developer
     Args:
     ----
         self:pointer to current instance of the class
     """
     image_file = random.choice(self.train_files)
     image = plt.imread(self.root_location + image_file)
     plt.figure(1)
     plt.imshow(image)
     my_roi = RoiPoly(color='r')
     mask = my_roi.get_mask(image[:, :, 2]) * 1
     plt.figure(2)
     plt.imshow(mask, cmap="gray")
     plt.show()
Exemplo n.º 15
0
def label(dpath, mpath):

    x = Image.open(dpath)

    im = np.array(x)
    im = im[:, :, 0]
    plt.imshow(im)
    my_roi = RoiPoly(color='r')

    mask = my_roi.get_mask(im)
    f_img = Image.fromarray(mask)

    #Output path of mask

    # Save mask to the path
    f_img.save(mpath + dpath.split('/')[-1].split('.')[0] + ".jpg")
Exemplo n.º 16
0
def main():
    dir_train = "./2019Proj1_train/"
    dir_labeled_train = "./labeled_train/"

    if not os.path.exists(dir_labeled_train):
        os.makedirs(dir_labeled_train)

    filelist = os.listdir(dir_train)
    num_file = len(filelist)

    startIdx = 0
    endIdx = num_file - 1
    if len(sys.argv) > 1 and sys.argv[1].isdigit():
        startIdx = int(sys.argv[1])

    if len(sys.argv) > 2 and sys.argv[2].isdigit():
        endIdx = int(sys.argv[2])

    print(endIdx)
    for i in range(max(0, startIdx), min(num_file - 1, endIdx) + 1):
        filename = filelist[i]
        name, extension = os.path.splitext(filename)
        image = Image.open(dir_train + filename)

        plt.title("Labeling: " + str(i) + ". " + name)
        plt.imshow(image)
        roi = RoiPoly(color='r')

        # show result
        plt.title("Result: " + str(i) + ". " + name)
        plt.imshow(image)
        roi.display_roi()
        plt.show()

        # get mask
        imgSize = np.shape(image)
        mask = roi.get_mask(np.zeros(imgSize[0:2], dtype=bool))

        # show mask
        # plt.title("Mask: " + str(i) + ". " + name)
        # plt.imshow(mask)
        # plt.show()

        np.save(os.path.join(dir_labeled_train, name + '.npy'), mask)
        print("Finish labeling: " + dir_labeled_train + name + '.npy')
        plt.close()
Exemplo n.º 17
0
    def set_white_info(self, white_reflectance):
        self.white_reflectance = white_reflectance
        root = tk.Tk()
        root.withdraw()
        white_reference_path = filedialog.askopenfilename(
            initialdir=self.cam_folder,
            title="Select white reference image for '{}' camera".format(
                self.cam_name))
        root.destroy()
        self.white_reference_path = white_reference_path

        loop = True
        while loop:
            is_full_white_img = input(
                "Does the white reference panel fills up the image? ('yes' / 'no')\n"
            )
            if is_full_white_img == 'yes':
                loop = False
                is_full_white_img = True
            elif is_full_white_img == 'no':
                loop = False
                is_full_white_img = False
            else:
                print("Please type either 'yes' or 'no'.")
        self.is_full_white_img = is_full_white_img

        white_exp_t = self.read_exp_t_ms(white_reference_path)
        self.white_exp_t = white_exp_t

        white_array = ufunc.read_img2array(white_reference_path)
        self.white_array = white_array

        if not is_full_white_img:
            bands = white_array.shape[2]
            band = int(bands / 2)

            fig = plt.figure()
            plt.imshow(white_array[:, :, band], cmap=plt.get_cmap("Greys_r"))
            plt.show(block=False)

            roi = RoiPoly(color='r', fig=fig)

            mask = roi.get_mask(white_array[:, :, band])
            white_mean_values = np.mean(white_array[mask], axis=0)
            self.white_mean_values = white_mean_values
Exemplo n.º 18
0
def labeling(m=3):
    '''Iterate over all training images and label m rois in each image'''
    mask_list = []
    for i in range(n):
        i += 1
        img_name = str(i)+'.png'
        img = plt.imread(os.path.join('trainset',img_name))
        masks = []
        for j in range(m):
            plt.imshow(img)
            r = RoiPoly(color='r')
            mask = r.get_mask(img[:,:,0]) # create mask of roi
            masks.append(mask)
        #combine masks
        mask_result = masks[0] | masks[1]
        mask_result = mask_result | masks[2]
        mask_list.append(mask_result)
    pickle_out = open('mask_list',"wb")
    pickle.dump(mask_list, pickle_out)
    pickle_out.close()
    return mask_list
Exemplo n.º 19
0
# plt.imshow(mask) # show the binary signal mask
# plt.show()

for image in glob.glob('../hw1_starter_code/train/non_barrel_blue/28.png'):
    img = cv2.imread(image)

    # get the RGB image in order to show the original image.
    RGB_image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    HSV_image = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

    # show RGB image
    plt.imshow(RGB_image)
    #plt.imshow(HSV_image)
    #plt.show()

    my_roi = RoiPoly(color='r')

    # create an area which has the same dimension as the original image
    area = np.zeros((HSV_image.shape[0], HSV_image.shape[1]))
    mask = my_roi.get_mask(area)

    plt.imshow(mask)
    #plt.show()

    mask = np.array(mask, dtype=np.uint8)
    #print(mask.shape)

    area_of_interest = cv2.bitwise_and(HSV_image, HSV_image, mask=mask)
    #plt.imshow(area_of_interest)
    #plt.show()
    #print(area_of_interest.shape)
# K3 = np.empty((0,3), int)
# K4 = np.empty((0,3), int)
K5 = np.empty((0, 3), int)

for i in range(1, 41):
    I1 = np.array(Image.open('./trainset/%d.png' % i), dtype='int')
    gray = I1[:, :, 0]

    # Show the image
    fig = plt.figure()
    plt.imshow(I1, interpolation='nearest')
    plt.title('Image %i, draw first ROI' % i)
    plt.show(block=False)

    # Let user draw first ROI
    roi1 = RoiPoly(color='r', fig=fig)

    # Show the image
    fig = plt.figure()
    plt.imshow(I1, interpolation='nearest')
    plt.title('Image %i, draw second ROI' % i)
    plt.show(block=False)

    # # Let user draw second ROI
    # roi2 = RoiPoly(color='b', fig=fig)
    #
    # # Show the image
    # fig = plt.figure()
    # plt.imshow(I1, interpolation='nearest')
    # plt.title('Image %i, draw third ROI' %i)
    # plt.show(block=False)
Exemplo n.º 21
0
        img = plt.imread(imagepath)
        # resized = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)

        img = img.astype(np.float32)

        img = normalize_image(img)

        fig = plt.figure()
        plt.imshow(img)
        # plt.colorbar()
        plt.title(
            "left click: line segment         right click or double click: close region"
        )
        plt.show(block=False)

        roi1 = RoiPoly(color='b', fig=fig)

        fig = plt.figure()
        plt.imshow(img)
        # plt.colorbar()
        plt.title(
            "left click: line segment         right click or double click: close region"
        )
        plt.show(block=False)

        roi2 = RoiPoly(color='b', fig=fig)

        fig = plt.figure()
        plt.imshow(img)
        # plt.colorbar()
        plt.title(
Exemplo n.º 22
0
def main():

    # logging.basicConfig(format='%(levelname)s ''%(processName)-10s : %(asctime)s ','%(module)s.%(funcName)s:%(lineno)s %(message)s',level=logging.INFO)

    # load images
    data_path  = '/home/pratique/drone-course/Window_detection/GMM/daylight_100'
    reply = 'k'
    i = 0
    for filename in os.listdir(data_path):
        # print filename
        if i%10 != 0:
            i+=1
            continue
        img = cv2.imread(os.path.join(data_path,filename))
        # convert = tune_RGB(img)
    	#convert = tune_HSV(img)
    	convert = adjust_gamma(img, gamma = 1.5)
    	# convert = cv2.fastNlMeansDenoisingColored(convert, None, 3, 3, 7, 15)
        convert = cv2.medianBlur(convert,5)
        img = cv2.cvtColor(convert,cv2.COLOR_BGR2RGB)
        # Show the image
        # Show the image
        # img = img[:,:,[2,1,0]]
        fig = plt.figure()
        plt.imshow(img, interpolation='nearest', cmap="Greys")
        plt.colorbar()
        plt.title("left click: line segment         right click or double click: close region")
        plt.show(block=False)

        # Let user draw first ROI
        roi1 = RoiPoly(color='r', fig=fig)

        # Show the image with the first ROI
        fig = plt.figure()
        plt.imshow(img, interpolation='nearest', cmap="Greys")
        plt.colorbar()
        roi1.display_roi()
        plt.title('draw second ROI')
        plt.show(block=False)

        # Let user draw second ROI
        roi2 = RoiPoly(color='b', fig=fig)

        # Show the image with both ROIs and their mean values
        plt.imshow(img, interpolation='nearest', cmap="Greys")
        plt.colorbar()
        for roi in [roi1, roi2]:
            roi.display_roi()
            roi.display_mean(img)
        plt.title('The two ROIs')
        plt.show()

        # plt.imshow(np.bitwise_not(roi2.get_mask(img) ^ roi1.get_mask(img)),
        #            interpolation='nearest', cmap="Greys")
        # plt.title('ROI masks of the two ROIs')
        # plt.show()

        #store data
        mask = roi2.get_mask(img) ^ roi1.get_mask(img)
        mask.astype(int)
        # print(np.uint8(mask))
        window_mask = np.uint8(mask*255) 
        extracted_frame = cv2.bitwise_and(img, img, mask = window_mask)
        extracted_frame = cv2.cvtColor(extracted_frame,cv2.COLOR_RGB2BGR)
        # input('aa')
        cv2.imwrite("./data/window_100"+str(i)+".jpg", extracted_frame)
        i = i+1
        if 0xFF == ord('q'):
            break
Exemplo n.º 23
0
def main():

    # Read source image :
    source = np.array(Image.open('Pictures/orca.jpg'))
    nb_row_s, nb_col_s, nb_ch_s = source.shape

    s = plt.figure()
    plt.imshow(source)
    plt.axis('off')

    # Select and display polygon in source picture
    poly = RoiPoly(color='r')
    source_1c = source[:, :, 0]
    polygonMask = poly.get_mask(source_1c)

    x_poly = np.around(poly.x)
    y_poly = np.around(poly.y)

    # Bounding rectangle of poly
    i_p_min = int(min(y_poly))
    i_p_max = int(max(y_poly))
    j_p_min = int(min(x_poly))
    j_p_max = int(max(x_poly))

    # Read target image :
    target = np.array(Image.open('Pictures/mountains.jpg'))
    nb_row_t, nb_col_t, nb_ch_t = target.shape

    t = plt.figure()
    plt.imshow(target)
    plt.axis('off')

    # Select rectangle r in target
    print('Select opposite corners of the target zone')
    [p1, p2] = plt.ginput(2)
    j_r_min = int(max(min(p1[0], p2[0]), 0))
    j_r_max = int(min(max(p1[0], p2[0]), nb_col_t))
    i_r_min = int(max(min(p1[1], p2[1]), 0))
    i_r_max = int(min(max(p1[1], p2[1]), nb_row_t))

    plt.plot([j_r_min, j_r_min], [i_r_min, i_r_max], color='red')
    plt.plot([j_r_min, j_r_max], [i_r_min, i_r_min], color='red')
    plt.plot([j_r_max, j_r_max], [i_r_min, i_r_max], color='red')
    plt.plot([j_r_min, j_r_max], [i_r_max, i_r_max], color='red')
    plt.draw()

    # Target sub-matrix corresponding to the rectangle r :
    r = target[i_r_min:i_r_max, j_r_min:j_r_max, :]

    # Select the sub-matrices in the bounding box of the polygon :
    source = source[i_p_min:i_p_max, j_p_min:j_p_max, :]
    polygonMask = polygonMask[i_p_min:i_p_max, j_p_min:j_p_max]

    # Resize s and p :
    nb_row_r, nb_col_r, nb_ch_r = r.shape
    source = resize(source, r.shape, anti_aliasing=True, mode='constant')
    polygonMask = resize(polygonMask,
                         r.shape,
                         anti_aliasing=True,
                         mode='constant')

    plt.show()
Exemplo n.º 24
0
from roipoly import RoiPoly
from matplotlib import pyplot as plt
import matplotlib
import numpy as np
from PIL import Image
import os

matplotlib.use('Qt5Agg')
points = np.empty((0, 3))
for filename in os.listdir('train_images'):
    filename = 'train_images/' + filename
    image = plt.imread(filename)

    plt.imshow(image)
    my_roi = RoiPoly(color='r')  # draw new ROI in red colo
    mask = my_roi.get_mask(image[:, :, 0])
    img = plt.imread(filename)
    points = np.vstack((points, img[mask]))

np.savetxt('ball.csv', points, delimiter=',')
#class Task(object):

if __name__ == '__main__':
    results = multiprocessing.Queue()

    # configure below for your experiment
    detectorName = 'MPCCD-8N0-3-002-6'
    integrateOver = 10
    t0offset = -10

    fig = plt.figure()
    tenFrames, curTag = returnTenFrames(detectorName,
                                        integrateOver=integrateOver)
    plt.imshow(tenFrames)
    my_roi = RoiPoly(color='r', fig=fig)
    plt.imshow(tenFrames)
    my_roi.display_roi()
    mask = my_roi.get_mask(tenFrames)

    #binning parameters
    roiBins = 40
    startBin = -2.0
    endbin = 3.0
    binCounterBin = np.zeros(roiBins)

    binTheData = binROI(results, detectorName, curTag, startBin, endbin, mask,
                        roiBins, t0offset)
    binTheData.start()
    binROIs = np.zeros(roiBins)
    bin_nomDel = np.zeros(roiBins)
Exemplo n.º 26
0
    im_zoom = im['tifstack'][:,
                             int(yvls[0]):int(yvls[1]),
                             int(xvls[0]):int(xvls[1])]
    plt.imshow(im_zoom_mean, origin='lower')

    if not USE_PREVIOUS_ROI:

        num_rois = input("Enter number of ROIs ")

        my_roi = []
        masks = []
        mn_roi = {}
        for crind in np.arange(int(num_rois)):
            plt.imshow(im_zoom_mean, origin='lower')
            print('press ENTER when ROI completed')
            my_roi.append(RoiPoly(color=colors[crind]))

            input()
            my_roi[-1].display_roi()
        for crind in np.arange(int(num_rois)):
            masks.append(my_roi[crind].get_mask(im_zoom_mean))
    else:
        my_roi = sumdt['roi']
        mn_roi = {}
        num_rois = len(my_roi)
        masks = sumdt['roi_masks']
    fig = plt.figure()
    ax1 = fig.add_subplot(311)
    plt.imshow(im_zoom_mean, origin='lower')
    for cr_roi in my_roi:
        cr_roi.display_roi()
Exemplo n.º 27
0
    # brightfield cell crop
    for cell_mask_frame in cell_frames_masked:
        cell_mask_frame = cell_mask_frame[row1:row2, col1:col2]
        cell_frames_masked_crop.append(cell_mask_frame)
    # plt.imshow(cell_frames_masked_crop[-1])
    # plt.show()
    # fluorescent crop
    fluo_masked_crop = []
    # for fluo_mask_frame in fluo_masked:
    #     fluo_mask_frame = fluo_mask_frame[row1:row2, col1:col2]
    #     fluo_masked_crop.append(fluo_mask_frame)

    # pick 1 bead inside cell
    plt.imshow(cell_frames_masked_crop[-1])  # show image
    plt.title("Select ROI for 1 bead inside the cell")
    cell_bead_roi = RoiPoly(color='b')
    cell_bead_mask = cell_bead_roi.get_mask(cell_frames_masked_crop[-1])
    cell_bead_masked = []
    for cell_mask_frame in cell_frames_masked_crop:
        cell_mask_frame[~cell_bead_mask] = cell_mask_frame.max()
        cell_bead_masked.append(cell_mask_frame)
    # crop cell bead
    chull = morphology.convex_hull_image(cell_bead_mask)
    [rows, columns] = np.where(chull)
    row1 = min(rows)
    row2 = max(rows)
    col1 = min(columns)
    col2 = max(columns)
    cell_bead_crop = []
    for cell_masked_frame in cell_frames_masked_crop:
        cell_masked_frame = cell_masked_frame[row1:row2, col1:col2]
Exemplo n.º 28
0
if __name__ == '__main__':  # since there's nothing above, this function can only be executed as main script

    for i in range(1, 61):  # 1-60

        # read the first training image
        folder = 'data/training'
        filename = '%04i.jpg' % (i, )
        img = cv2.imread(os.path.join(folder, filename))
        img = cv2.cvtColor(
            img, cv2.COLOR_BGR2RGB
        )  # images are in BGR format, need to convert to RGB

        # display the image and use roipoly for labeling
        fig, ax = plt.subplots()
        ax.imshow(img)
        my_roi = RoiPoly(fig=fig, ax=ax, color='r')

        # get the image mask
        mask = my_roi.get_mask(img)

        # display the labeled region and the image mask
        fig, (ax1, ax2) = plt.subplots(1, 2)
        fig.suptitle('%d pixels selected\n' % img[mask, :].shape[0])

        ax1.imshow(img)
        ax1.add_line(
            plt.Line2D(my_roi.x + [my_roi.x[0]],
                       my_roi.y + [my_roi.y[0]],
                       color=my_roi.color))
        ax2.imshow(mask)
Exemplo n.º 29
0
# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""

import numpy as np
from matplotlib import pyplot as plt
from roipoly import RoiPoly
import matplotlib.image as mpimg

for index in range(1, 26):
    # load image
    img = mpimg.imread("C:/users/jiageng/Desktop/ECE276A_HW1/trainset/%s.png" %
                       index)
    fig = plt.figure()
    plt.imshow(img)
    plt.show(block=False)
    # draw the roi from the image
    roi = RoiPoly(color='b', fig=fig)
    mask_roi = roi.get_mask(img[:, :, 1])
    plt.imshow(mask_roi, interpolation='nearest', cmap="Greys")
    plt.show()
    #store masks
    np.save("C:/users/jiageng/Desktop/ECE276A_HW1/masks/%s.npy" % index,
            mask_roi)
    print(index)
Exemplo n.º 30
0
plt.title("left click: line segment         right click: close region")
plt.show(block=False)

color_map = brewer2mpl.get_map('Accent', 'qualitative', 6)
colors = itertools.cycle(color_map.mpl_colors)

roinum = 0
roiarray = []

while roinum < int(num):

    # with open('/home/jetherng/roipoly.py/examples/coordinate.txt', 'a') as f:

    #    f.write("\nroi "+str(roinum)+":\n")
    # Let user draw ROI
    roiarray.append(RoiPoly(color=next(colors), fig=fig))

    # Show the image with the ROIs
    fig = plt.figure(figsize=figsize)
    plt.imshow(img, interpolation='nearest', cmap="Greys")
    roiarray[roinum].display_roi()
    plt.title('draw ROI')
    plt.show(block=False)
    fig = [x.display_roi() for x in roiarray]
    #[x.display_mean(img) for x in roiarray]
    roinum = roinum + 1

#fig[-1].savefig('out.png', bbox_inches='tight', pad_inches=0)

print("done!")