Example #1
0
def color_mask(img, text):
    # show the image
    pl.imshow(img)
    pl.colorbar()
    pl.title(text + " left click: line segment    right click: close region")

    # let user draw first ROI
    ROI = roipoly(roicolor='r')  #let user draw first ROI

    return ROI.getMask(img)
Example #2
0
def focusROI(data, vessels):
    plt.imshow(vessels)
    plt.title(
        "Left lick to create a ROI polygon ... then right click to finish !")
    roi = roipoly.roipoly(roicolor='r')
    mask = roi.getMask(vessels).astype(float)
    mask[mask == False] *= np.nan
    vessels *= mask
    maskdata = binArray(mask, 1, 4, 4, np.mean)
    maskdata = binArray(maskdata, 0, 4, 4, np.mean)
    data *= maskdata.reshape((1, 1, maskdata.shape[0], maskdata.shape[1], 1))
    return data, vessels
Example #3
0
    def process_img(self, fname, showMask=0):
        # Creates a mask for the image pointed to by fname
        # If showMask = 1, roi's are shown after processing
        fpath = self.data_path + fname
        img_file = imread(fpath)
        img_file = np.sum(img_file, 2).astype(np.float64)
        img_file = normalize_image(img_file)

        roi_name = 'roi_' + fname[:-5] + '.npy'
        bw_name = 'bw_' + fname[:-5] + '.jpg'

        # Loading or Defining ROI
        if roi_name not in os.listdir(self.data_path):
            print('ROI file for ' + fname +
                  ' not found. Please manually define ROI.')
            plt.imshow(img_file)
            roi = roipoly()
            img_roi = roi.getMask(img_file)

            np.save(roi_name, img_roi)
        else:
            print('ROI file for ' + fname + ' found. Loading ROI...')
            img_roi = np.load(self.data_path + roi_name)

        maskImg = img_roi * img_file

        filtImg = np.zeros(maskImg.shape)

        # Idea - 3D fit instead of 2D?
        for i in range(maskImg.shape[0]):
            filtImg[i, :] = processRow(maskImg[i, :], 0.5)

        imgThresh = 0.65

        bw_img = filtImg > imgThresh
        imsave(self.data_path + bw_name, bw_img)

        if showMask != 0:
            plt.imshow(bw_img, cmap='gray')
            plt.show()
Example #4
0
                 )  #get group of picture name(list)
notsoRed_Class = [
    [], [], []
]  # initialize the red class as a list which contains three sub list for RGB
#Red_Class_area = []

for img_file in G_P:
    img = cv2.imread('trainset/' + img_file)
    img2 = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)  #converted image

    pl.imshow(img2)  #show the converted image
    pl.colorbar()  #show the color bar on the side of image
    pl.title("left click: line segment         right click: close region")

    # let user draw first ROI in red color
    MyROI1 = roipoly(roicolor='r')  #let user draw first ROI
    MyROI1.displayROI()  #show the margin of the mask
    pl.imshow(
        MyROI1.getMask(img2)
    )  #show the mask graph, only two color in this graph, intermediate
    pl.show()  #keep show the image, final decided

    mask_graph = MyROI1.getMask(img)  #display the masked graph
    positions = np.where(
        mask_graph == True)  #find the position index of masked graph for true

    img3 = cv2.cvtColor(img2, cv2.COLOR_BGR2YCR_CB)
    R_img_level = img3[:, :, 0]  #slice the origin graph into R level
    G_img_level = img3[:, :, 1]  #slice the origin graph into G level
    B_img_level = img3[:, :, 2]  #slice the origin graph into B level
Example #5
0
        if os.path.isfile(textfile):
            continue
        bgrImage = cv2.imread(inFolderPath + filename)
        rgbImg = cv2.cvtColor(bgrImage, cv2.COLOR_BGR2RGB)

        rois = []
        retry = True
        while (retry):
            retry = False
            plt.cla()

            # draw region of interest
            plt.imshow(rgbImg, interpolation='none')
            for roi in rois:
                roi.displayROI()
            plt.title(basename)
            rois.append(roipoly(roicolor='r'))  #let user draw ROI

            fig = plt.gcf()
            fig.canvas.mpl_connect('key_press_event', \
             lambda event: on_keypress(event, outFolderPath + basename, rgbImg))

            plt.cla()
            plt.imshow(rgbImg, interpolation='none')
            for roi in rois:
                roi.displayROI()
            plt.title(
                "press \'n\' to save and go to next picture, \'r\' to retry \n \'q\' to quit, \'a\' to add another region"
            )
            plt.show()
import pylab as pl
import numpy as np
from skimage.measure import label, regionprops
import pickle
import os

yellow = [[], [], []]

root = os.listdir('/Users/hebolin/Desktop/ECE276A_PR1/trainset')
del root[2]

for i in root:
    image = cv2.imread('./trainset/' + i)
    image2 = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)  # converted color space
    pl.imshow(image2)
    roi = roipoly(color='r')
    mask = roi.get_mask(image2)

    # Labelling
    position = np.where(mask == True)
    image3 = cv2.cvtColor(image2,
                          cv2.COLOR_RGB2YCR_CB)  # converted color space

    Y = image3[:, :, 0]
    CR = image3[:, :, 1]
    CB = image3[:, :, 2]

    Y_label = Y[position]
    CR_label = CR[position]
    CB_label = CB[position]
Example #7
0
import pylab as pl
from roipoly import roipoly 

# create image
img = pl.ones((100, 100)) * range(0, 100)

# show the image
pl.imshow(img, interpolation='nearest', cmap="Greys")
pl.colorbar()
pl.title("left click: line segment         right click: close region")

# let user draw first ROI
ROI1 = roipoly(roicolor='r')

# show the image with the first ROI
pl.imshow(img, interpolation='nearest', cmap="Greys")
pl.colorbar()
ROI1.displayROI()
pl.title('draw second ROI')

# let user draw second ROI
ROI2 = roipoly(roicolor='b')  # let user draw ROI

# show the image with both ROIs and their mean values
pl.imshow(img, interpolation='nearest', cmap="Greys")
pl.colorbar()
[x.displayROI() for x in [ROI1, ROI2]]
[x.displayMean(img) for x in [ROI1, ROI2]]
pl.title('The two ROIs')
pl.show()
Example #8
0
val = []

for filename in glob.glob(
        'C:\Users\Sai Krishnan\Desktop\Penn\Courses\Spring 2017\ESE 650\Project 1 - Color Segmentation\Alternative Training set\Train/*.png'
):

    img = cv2.imread(filename, cv2.COLOR_RGB2LAB)
    # Convert to RGB due to Pylab
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

    pl.imshow(img, interpolation='nearest', cmap="Greys")
    pl.colorbar()
    pl.title("left click: line segment         right click: close region")

    # let user draw first ROI
    ROI1 = roipoly(roicolor='r')

    # Convert back to BGR
    img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)

    # Split into channels
    img_b = img[:, :, 0]
    img_g = img[:, :, 1]
    img_r = img[:, :, 2]

    # Get masks for each channel
    mask_r = ROI1.getMask(img)
    mask_g = ROI1.getMask(img)
    mask_b = ROI1.getMask(img)

    temp = img[mask_r]
Example #9
0
    img = io.imread(path)
    nimg= img[:,:,0] 
    next = 0
    savemask = os.path.join('BarrelRed', 'mask', str(i))
    savecolorseg = os.path.join('BarrelRed', 'colorseg', str(i))
#    saveit = os.path.join('BarrelRed', 'mask', str(i))

    

    while (next==0):
    
        plt.imshow(img)
    
    
    #plt.imshow(img)
        MyROI = roipoly(roicolor = 'r')
        plt.imshow(img)
        MyROI.displayROI()
        plt.show()
        print 'Image '+ str(i) +':\n'
        userin = input("0 - Next\n1 - Second Barrel\n2 - Red (not Barrel)\n3 - Yellow\n4 - Brown\n5 - Redo\n6 - Quit\n")
        

        if userin == 5:
            print "Redo"
            print savemask
            continue          
        elif userin == 6:
            break

	labeledFolder = "labeled_img/"
	colorFolder2 = "Barrel_Blue/"	
	colorFolder1 = "LR_Blue/"
	for filename in os.listdir(imgFolder):
		Imagename, extension = os.path.splitext(filename)
		outPath = labeledFolder + colorFolder1
		redo = True
		rois = []
		labelImgname = outPath + Imagename + ".npy"
		if os.path.isfile(labelImgname):
			continue
		bgrImage = cv2.imread(imgFolder + filename)
		rgbImg = cv2.cvtColor(bgrImage, cv2.COLOR_BGR2RGB)
		while (redo):
			fig =plt.figure()
			plt.imshow(rgbImg)
			for roi in rois:
				roi.displayROI()
			plt.title(Imagename + ".png")
			rois.append(roipoly(roicolor='r'))
			fig = plt.gcf()
			fig.canvas.mpl_connect('key_press_event',lambda event: onKey(event, labelImgname, rgbImg))
			plt.imshow(rgbImg)
			plt.title("Press \'d\' to save and move on \n \'r\' to redo|\'a\' to add another region")
			for roi in rois:
				roi.displayROI()
			plt.show()



with open(os.path.join(path, filename), 'r') as f:
    lines = f.readlines()  # read lines into a list
    
    assert len(lines) != 0, 'labels.txt is empty'
    
    # strip '\n', split each line by whitespace 
    lines = [l.strip('\n').split(' ') for l in lines] 

    for line in lines:
        assert len(line) == 3, \
            'A line in labels.txt does not contain 3 entries: %s' % line

# training with every 4th image
image_step_size = 4
            
for i in range(0, len(lines), image_step_size):  # looping through images with a step size
# for i in range(len(lines)):  # using every image 
    
    l = lines[i]
    print "File name: " + str(l[0])
    
    # read the image and mark the red regions with polygons
    img = cv2.imread(os.path.join(path, l[0]))
    pl.imshow(img)
    MyROI = roipoly(roicolor='r') #let user draw ROI 
    masks.append(MyROI.getMask(cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)))

# save the masks with numpy into .npy for the training code
np.save("phone_screen_masks.npy",masks)
def PixelDataGenerator():
    redPixelValues = []
    brownPixelValues = []
    grayPixelValues = []

    for filename in os.listdir(trainingFolder):
        img = Image.open(os.path.join(trainingFolder, filename))
        pix = img.load()

        ######### RED ROI #########
        pl.imshow(img, interpolation='nearest', cmap="Greys")
        pl.title("left click: line segment         right click: close region")
        ROI1 = roipoly(roicolor='red')

        xPointsAverage = int((ROI1.allxpoints[0] + ROI1.allxpoints[1] +
                              ROI1.allxpoints[2] + ROI1.allxpoints[3]) / 4)
        yPointsAverage = int((ROI1.allypoints[0] + ROI1.allypoints[1] +
                              ROI1.allypoints[2] + ROI1.allypoints[3]) / 4)
        print("Red Coordinates - ")
        print(xPointsAverage)
        print(yPointsAverage)
        print("Red Value - ")
        redPixelValues.append(pix[xPointsAverage, yPointsAverage])
        print(redPixelValues)
        print("")
        ######### RED ROI #########

        ######### BROWN ROI #########
        brownResponse = input('Press 1 if there is brown, 0 if not: ')
        if brownResponse is 1:
            pl.imshow(img, interpolation='nearest', cmap="Greys")
            ROI1.displayROI()
            pl.title('draw second ROI')
            ROI2 = roipoly(roicolor='brown')

            xPointsAverage = int((ROI2.allxpoints[0] + ROI2.allxpoints[1] +
                                  ROI2.allxpoints[2] + ROI2.allxpoints[3]) / 4)
            yPointsAverage = int((ROI2.allypoints[0] + ROI2.allypoints[1] +
                                  ROI2.allypoints[2] + ROI2.allypoints[3]) / 4)
            print("Brown Coordinates - ")
            print(xPointsAverage)
            print(yPointsAverage)
            print("Brown Value - ")
            brownPixelValues.append(pix[xPointsAverage, yPointsAverage])
            print(brownPixelValues)
            print("")
        ######### BROWN ROI #########

        ######### GRAY ROI #########
        grayResponse = input('Press 1 if there is gray, 0 if not: ')
        if grayResponse is 1:
            pl.imshow(img, interpolation='nearest', cmap="Greys")
            ROI1.displayROI()
            if brownResponse is 1: ROI2.displayROI()
            pl.title('draw third ROI')
            ROI3 = roipoly(roicolor='gray')

            xPointsAverage = int((ROI3.allxpoints[0] + ROI3.allxpoints[1] +
                                  ROI3.allxpoints[2] + ROI3.allxpoints[3]) / 4)
            yPointsAverage = int((ROI3.allypoints[0] + ROI3.allypoints[1] +
                                  ROI3.allypoints[2] + ROI3.allypoints[3]) / 4)
            print("Gray Coordinates - ")
            print(xPointsAverage)
            print(yPointsAverage)
            print("Gray Value - ")
            grayPixelValues.append(pix[xPointsAverage, yPointsAverage])
            print(grayPixelValues)
            print("")
        ######### GRAY ROI #########

        f = open('TrainsetOutput.txt', 'w')
        json.dump("RED - ", f)
        json.dump(redPixelValues, f)
        json.dump("BROWN - ", f)
        json.dump(brownPixelValues, f)
        json.dump("GRAY - ", f)
        json.dump(grayPixelValues, f)
        f.close()
os.chdir(dir_for_images)
ConstPixelDims=(int(128), int(128), int(51))
array_dicom=np.zeros(ConstPixelDims,dtype=int)
i=0
for filename in os.listdir(dir_for_images):
	temp = dicom.read_file(filename)
	array_dicom[:,:,i]=temp.pixel_array
	i=i+1


# no method file, hard code ppm offsets:
ppm=np.linspace(-6,6,50)  #these are f****d, go out to 8ppm or so

pl.imshow(array_dicom[:,:,1])
MyROI = roipoly(roicolor='r') # draw new ROI in red color
mask = MyROI.getMask(array_dicom[:,:,1])
Z_signal=[]
for i in range(0,50):
	temp_image=array_dicom[:,:,i]
	Z_signal.append(pl.mean(temp_image[mask]))

#normalize
Z_signal=Z_signal/max(Z_signal)

X0=[.5,.1,.1,.1,2.15,.5,.5,0.5,0,1.8,4.2,5.6]
popt, pcov = curve_fit(make_lorentzian_func(4,False), ppm, Z_signal, X0)
simmed_data=make_lorentzian_func(4,True)(ppm,popt)

print("CEST 4.2: ", popt[2])
print("CEST 5.6: ", popt[3])
import matplotlib.image as mpimg
import numpy as np
import os
from roipoly import roipoly

# Folder containing images
folder = "Image_data"
for filename in os.listdir(folder):
    # create image
    img = mpimg.imread(os.path.join(folder, filename))
    print filename
    print img.shape
    # Show image and ask user to make a polygon for the 5 different classes
    pl.imshow(img)
    pl.title("Mark Barrel Right Click When Done")
    ROI_red = roipoly(roicolor='r')
    pl.imshow(img)
    pl.title("Mark Yellow Patch Right Click When Done")
    ROI_yellow = roipoly(roicolor='y')
    pl.imshow(img)
    pl.title("Mark Black Right Click When Done")
    ROI_black = roipoly(roicolor='k')
    pl.imshow(img)
    pl.title("Mark Brown Patch Right Click When Done")
    ROI_brown = roipoly(roicolor='m')
    pl.imshow(img)
    pl.title("Mark Other Red Right Click When Done")
    ROI_ored = roipoly(roicolor='r')
    # If a polygon is made store the points inside the polygon using a binary mask and the original image
    # Save the data in a text file
    # Stores the data in RGB format. MatplotLib stores in BG. OpenCV requires RGB
Example #15
0
#%%

# T98G
filename = '/Users/xies/Box/Others/SZ_FACS_RB/SZ-091320 Async OPP_Group_T98G OPP647 2nd488.fcs'
tg_bg = FCMeasurement(ID='Test Sample', datafile=filename)

size_bins = np.linspace(tg_bg['FSC-A'].min(),tg_bg['FSC-A'].max(),num = 26)
bg_rb = get_bin_means(tg_bg['FSC-A'],tg_bg['BL1-A'],size_bins)

filename = '/Users/xies/Box/Others/SZ_FACS_RB/SZ-091320 Async OPP_Group_T98G OPP647 RB488.fcs'
tg = FCMeasurement(ID='Test Sample', datafile=filename)

dapi = tg['VL1-A']
fsc = tg['FSC-A']
plt.scatter(dapi,fsc,alpha=0.002)
g1_gate = roipoly(color='r')
g1_gate_p = mplPath.Path( np.vstack((g1_gate.x,g1_gate.y)).T )
g1_gateI = g1_gate_p.contains_points( np.vstack((tg['VL1-A'],tg['FSC-A'])).T )
tg_g1 = tg[g1_gateI]

plt.scatter(dapi,fsc,alpha=0.002)
g2_gate = roipoly(color='r')
g2_gate_p = mplPath.Path( np.vstack((g2_gate.x,g2_gate.y)).T )
g2_gateI = g2_gate_p.contains_points( np.vstack((tg['VL1-A'],tg['FSC-A'])).T )
tg_g2 = tg[g2_gateI]

rb_g1,_ = get_bin_means(tg_g1['FSC-A'],tg_g1['BL1-A'],size_bins)
rb_g2,_ = get_bin_means(tg_g2['FSC-A'],tg_g2['BL1-A'],size_bins)
sizes = np.array( [ (x+y)/2 for x,y in zip( size_bins[0:-1],size_bins[1:] ) ] )

Example #16
0
def main():

    folder = "data/Proj1_Train/"
    # list all image files
    image_files = os.listdir(folder)

    # check the existance of pickle files
    pickle_folder = "data/pickle_folder"
    if not os.path.exists(pickle_folder):
        os.makedirs(pickle_folder)

    data_set_file = "train" + ".pickle"
    pickle_file = os.path.join(pickle_folder, data_set_file)
    if os.path.exists(pickle_file):
        print 'train file existed. reading...'
        with open(pickle_file, 'rb') as f:
            train = pickle.load(f)
    else:
        train = np.array([])

    data_set_file = "target" + ".pickle"
    pickle_file = os.path.join(pickle_folder, data_set_file)
    if os.path.exists(pickle_file):
        with open(pickle_file, 'rb') as f:
            target = pickle.load(f)
    else:
        target = np.array([])

    data_set_file = "ids" + ".pickle"
    pickle_file = os.path.join(pickle_folder, data_set_file)
    if os.path.exists(pickle_file):
        with open(pickle_file, 'rb') as f:
            ids = pickle.load(f)
    else:
        ids = np.array([])

    num_images = 0
    for image in image_files:
        image_file = os.path.join(folder, image)
        print "\n %d. Image file: " % (num_images + 1), image_file
        num_images += 1

        # open image
        img = cv2.imread(image_file)
        img_denoised = cv2.fastNlMeansDenoisingColored(img, None, 5, 5, 3, 5)
        # cv2.imshow('original image',img)
        # cv2.imshow('denoised image', img_denoised)
        # cv2.waitKey(0)
        # cv2.destroyAllWindows()
        # exit(0)

        img = cv2.cvtColor(img_denoised, cv2.COLOR_BGR2RGB)
        # OpenCV represents RGB images as multi-dimensional Numpy but in reverse order: BGR rather than RGB.
        # Thus, we have to convert it back to RGB
        pl.imshow(img, aspect='auto')
        pl.title(
            "left click: line segment         right click: close region. Let draw barrel RED"
        )

        # let user draw first ROI which is barrel RED
        print '-- Draw ROI:  '
        ROI = roipoly(roicolor='r')  #let user draw first ROI

        color = int(
            raw_input(
                "---- What color it is? (barrel: 1, floor red: 2, wall red: 3, chair red: 4, yellow: 5, wall gray brick: 6, green grass: 7) : "
            ))

        # show the image with the first ROI
        pl.imshow(img, aspect='auto')
        ROI.displayROI()
        # print np.shape(img)
        grid = makeGrid(ROI, img)

        # # Uncomment the following two lines before running test_saved_pickle()
        # img[grid] = (0,0,0)
        # ROI.append(img)
        # # Comment the following lines before running test_saved_pickle()

        # append data
        # train data
        locate_pixels = np.where(grid)
        num_pixels = np.shape(locate_pixels)[1]
        img_ids = np.array([image for i in range(num_pixels)])
        color_ids = np.array([color for i in range(num_pixels)])

        # train
        try:
            train = np.concatenate(
                (train, np.vstack(
                    ([locate_pixels[0].T], [locate_pixels[1].T])).T),
                axis=0)
        except:
            train = np.vstack(([locate_pixels[0].T], [locate_pixels[1].T])).T
        # target
        try:
            target = np.concatenate((target, color_ids), axis=0)
        except:
            target = color_ids
        try:
            ids = np.concatenate((ids, img_ids), axis=0)
        except:
            ids = img_ids
        # print train[0]
        # print train[-1]
        # print np.shape(train)
        # print np.shape(target)
        # print np.shape(ids)
        # print 'grid and image shape'
        # print np.shape(grid)
        # print np.shape(img)
        # print np.shape(img_ids)
        # print grid[0]

        pl.imshow(img, aspect='auto')
        print "-- Sofar, total number of element in the train set: ", np.shape(
            train)

        # add RGB of the pixels to the corresponding data array

        while True:
            command = raw_input("-- Draw ROI for another color Y/N ?:  ")
            command = command.lower()
            if command == 'n' or command == 'N':
                break
            # else, let user draw next ROI
            print "--- Draw next ROI...."
            print "----  barrel: 1, floor red: 2, wall red: 3, chair red: 4, yellow: 5, wall gray brick: 6 , green grass: 7!! "
            ROI = roipoly(roicolor='b')  #let user draw ROI
            color = int(
                raw_input(
                    "---- What color it is? (barrel: 1, floor red: 2, wall red: 3, chair red: 4, yellow: 5, wall gray brick: 6, green grass: 7) : "
                ))
            pl.imshow(img, aspect='auto')
            ROI.displayROI()
            print "----- Color has been segmented:", color, " or ", color_dict[
                color]

            grid = makeGrid(ROI, img)

            # append data
            # train data
            locate_pixels = np.where(grid)
            num_pixels = np.shape(locate_pixels)[1]
            img_ids = np.array([image for i in range(num_pixels)])
            color_ids = np.array([color for i in range(num_pixels)])

            # train
            train = np.concatenate(
                (train, np.vstack(
                    ([locate_pixels[0].T], [locate_pixels[1].T])).T),
                axis=0)
            # target
            target = np.concatenate((target, color_ids), axis=0)
            ids = np.concatenate((ids, img_ids), axis=0)

        # cv2.waitKey(27)
        # clear window to avoid inerference
        pl.clf()

        if num_images >= 10:
            command = raw_input("-- Continue segmentation?  Y/N ?:  ")
            command = command.lower()
            if command == 'n' or command == 'N':
                break

    # dump datasets to pickle files
    if not os.path.exists(pickle_folder):
        os.makedirs(pickle_folder)
    # remove old file
    data_set_file = "train" + ".pickle"
    pickle_file = os.path.join(pickle_folder, data_set_file)
    if os.path.exists(pickle_file):
        os.remove(pickle_file)
    # create new file
    dump_pickle(pickle_folder, "train", train)
    # remove old file
    data_set_file = "target" + ".pickle"
    pickle_file = os.path.join(pickle_folder, data_set_file)
    if os.path.exists(pickle_file):
        os.remove(pickle_file)
    # create new file
    dump_pickle(pickle_folder, "target", target)

    # remove old file
    data_set_file = "ids" + ".pickle"
    pickle_file = os.path.join(pickle_folder, data_set_file)
    if os.path.exists(pickle_file):
        os.remove(pickle_file)
    # create new file
    dump_pickle(pickle_folder, "ids", ids)
Example #17
0
def draw_rois_and_find_fluo(
    filename: str,
    time_per_frame: float,
    num_of_rois: int,
    colors: List,
    num_of_channels: int,
    channel_to_keep: int,
):
    """

    :param filename:
    :param time_per_frame: 1/Hz (1/framerate)
    :param num_of_rois: Number of GCaMP-labeled cells to mark
    :param colors:
    :param num_of_channels: How many channels does the stack contain
    :param channel_to_keep: Which channel (1..end) contains the GCaMP data?
    :return:
    """
    print("Reading stack...")
    if filename.endswith(".tif"):
        tif = tifffile.imread(filename)
        data = tif[channel_to_keep - 1::num_of_channels, :]
    elif filename.endswith(".h5") or filename.endswith(".hdf5"):
        with File(filename, "r") as h5file:
            data = h5file["mov"].value  # EP's motion correction output

    # If image isn't symmetric - expand it. Useful for PYSIGHT outputs
    if data.shape[1] != data.shape[2]:
        data = resize_image(data)

    print("Reading complete.")
    num_of_slices = data.shape[0]
    max_time = num_of_slices * time_per_frame  # second
    rois = []
    fluorescent_trace = np.zeros((num_of_rois, num_of_slices))

    # Display the mean image and draw ROIs

    mean_image = np.mean(data, 0)
    for idx in range(num_of_rois):
        fig_rois = plt.figure()
        ax_rois = fig_rois.add_subplot(111)
        ax_rois.imshow(mean_image, cmap="gray")
        rois.append(roipoly(roicolor=colors[idx]))
        plt.show(block=True)

    # Calculate the mean fluo. and draw the cells in a single figure
    print("Calculating mean...")
    fig_cells = plt.figure()
    ax_cells = fig_cells.add_subplot(121)
    ax_cells.set_title("Field of View")
    ax_cells.imshow(mean_image, cmap="gray")
    ax_cells.set_axis_off()

    for idx, roi in enumerate(rois):
        cur_mask = roi.getMask(mean_image)
        fluorescent_trace[idx, :] = np.mean(data[:, cur_mask], axis=-1)
        roi.displayROI()

    con_method = ConversionMethod.DFF  # what to do with the data
    final_fluo = RawTraceConverter(conversion_method=con_method,
                                   raw_data=fluorescent_trace).convert()

    time_vec = np.linspace(start=0, stop=max_time, num=num_of_slices).reshape(
        (1, num_of_slices))
    time_vec = np.tile(time_vec, (num_of_rois, 1))
    assert time_vec.shape == final_fluo.shape

    # Plot fluorescence results
    ax = fig_cells.add_subplot(122)
    ax.plot(time_vec.T, final_fluo.T)
    ax.set_xlabel("Time [sec]")
    ax.set_ylabel("Cell ID")
    ax.set_yticks(np.arange(num_of_rois) + 0.5)
    ax.set_yticklabels(np.arange(1, num_of_rois + 1))
    ax.set_title(r"$\Delta F / F")

    return mean_image, time_vec, final_fluo, rois
Example #18
0
from roipoly import roipoly
import pylab as pl
import numpy as np

image = pl.imread("e:/gpn/danger_zone.jpg")
image_arr = np.asarray(image)
pl.imshow(image)
MyROI = roipoly(roicolor='r')  # draw new ROI in red color
mask = MyROI.getMask(image_arr[:2, :2])
pl.imshow(mask)
Example #19
0
"""Test if the old example still works
(commit 80737fa9d66d839e52b40d7cadcf02e143a86b4a)"""
import pylab as pl
from roipoly import roipoly

# create image
img = pl.ones((100, 100)) * range(0, 100)

# show the image
pl.imshow(img, interpolation='nearest', cmap="Greys")
pl.colorbar()
pl.title("left click: line segment         right click: close region")

# let user draw first ROI
ROI1 = roipoly(roicolor='r')  # let user draw first ROI

# show the image with the first ROI
pl.imshow(img, interpolation='nearest', cmap="Greys")
pl.colorbar()
ROI1.displayROI()
pl.title('draw second ROI')

# let user draw second ROI
ROI2 = roipoly(roicolor='b')  # let user draw ROI

# show the image with both ROIs and their mean values
pl.imshow(img, interpolation='nearest', cmap="Greys")
pl.colorbar()
[x.displayROI() for x in [ROI1, ROI2]]
[x.displayMean(img) for x in [ROI1, ROI2]]
pl.title('The two ROIs')
Example #20
0
    for color in folder_colors:
        subfolder = folder_out + '/' + color
        if not os.path.exists(subfolder):
            os.makedirs(subfolder)

for filename in os.listdir(folder):
    if filename not in ("2.2.png", "2.6.png", "2.8.png", "5.4.png"):
        continue
    image = cv2.imread(os.path.join(folder, filename), cv2.IMREAD_COLOR)
    if image is not None:
        img_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

        pl.imshow(img_rgb)
        pl.title('draw red ROI')

        redROI = roipoly(roicolor='g')
        mask = redROI.getMask(img_rgb)
        red_data = img_rgb[mask]
        np.save(folder_out + '/' + folder_colors[0] + '/' + filename, red_data)

        pl.imshow(img_rgb)
        pl.title('draw black ROI')

        blackROI = roipoly(roicolor='r')
        mask = blackROI.getMask(img_rgb)
        black_data = img_rgb[mask]
        np.save(folder_out + '/' + folder_colors[1] + '/' + filename,
                black_data)

        pl.imshow(img_rgb)
        pl.title('draw brown ROI')