def crop(self, boxes): ''' In the crop filename, I add the id of the cell on the image. Otherwise it won't be possible to find it again afterwards, for classification purposes ''' folderName=self._findFolder() for im in boxes: if not self.settings.new_h5: #renumbering according to mitocheck image numbering local_im=30*im else: #renumbering according to xb screen image numbering local_im=im+1 image_name=filter(lambda x: self.settings.imageFilename.format(self.well.split('_')[0], local_im) in x, \ os.listdir(os.path.join(self.settings.rawDataFolder, self.plate, folderName)))[0] image=vi.readImage(os.path.join(self.settings.rawDataFolder, self.plate, folderName, image_name)) for crop_ in boxes[im]: id_, cell_id, crop_coordinates = crop_ X,x,x__, Y,y,y__=self._newImageSize(crop_coordinates) croppedImage = vigra.VigraArray((x__, y__, 1), dtype=np.dtype('uint8')) croppedImage[:,:,0]=(image[x:X, y:Y,0]-self.settings.min_)*(2**8-1)/(self.settings.max_-self.settings.min_) vi.writeImage(croppedImage, \ os.path.join(self.settings.outputFolder, self.plate, self.settings.outputImage.format(self.plate, self.well.split('_')[0],id_, im, cell_id)),\ dtype=np.dtype('uint8')) return
def crop_to_sequence(self, boxes, scores): ''' In the crop filename, I add the number of the image in the galerie so that they're by default ordered in time ''' if scores==None: scores=defaultdict(int) folderName=self._findFolder() for im in boxes: if not self.settings.new_h5: #renumbering according to mitocheck image numbering local_im=30*im splitting_index=0 else: #renumbering according to xb screen/PCNA image numbering local_im=im+1 splitting_index=1 image_name=filter(lambda x: self.settings.imageFilename.format(self.well.split('_')[splitting_index], local_im) in x, \ os.listdir(os.path.join(self.settings.rawDataFolder, self.plate, folderName)))[0] image=vi.readImage(os.path.join(self.settings.rawDataFolder, self.plate, folderName, image_name)) for crop_ in boxes[im]: id_, num, crop_coordinates = crop_ X,x,x__, Y,y,y__=self._newImageSize(crop_coordinates) croppedImage = vigra.VigraArray((x__, y__, 1), dtype=np.dtype('uint8')) croppedImage[:,:,0]=(image[x:X, y:Y,0]-self.settings.min_)*(2**8-1)/(self.settings.max_-self.settings.min_) vi.writeImage(croppedImage, \ os.path.join(self.outputFolder, self.plate, self.settings.outputImage.format(scores[id_], self.plate, self.well.split('_')[0],id_, im, num)),\ dtype=np.dtype('uint8')) return
def splitShape(img, outpath = "", option = 0): """divides a shape into two halfs. Input: grayscale image with one shape completely on it. Output: Numpy Array with labels of the labeleld shape (option == 0) or hull (option == 1). If outpath is specified, an image of the labelled shape (option == 0) or hull (option == 1) will be written to outpath""" #read image and get image size img_Xmax = img.shape[0] img_Ymax = img.shape[1] img_white = [[]] if option == 0: #producing an array of only the white pixels on the image i = 0 while i < img_Xmax: j = 0 while j < img_Ymax: if img[i, j, 0] != 0: img_white.append([i, j]) j += 1 i += 1 img_white.pop(0) img_white = numpy.array(img_white) #get hull and convex hull of img img_Hull = getHullpoints(img) img_convexHull = vigra.geometry.convexHull(numpy.array(img_Hull, dtype=float)) #determine deepest concavity and label the hull: 0 for convexity, natural number >= 1 for the according convexity #img_labelledHull will contain the labelled hullpoints, maxDist will contain the depth of the maximum concavity and its index #hullP will contain the coordinates of the two hullpoints bordering the deepest concavity img_labelledHull, maxDist, hullP = labelHull(img_Hull, img_convexHull) maxDepth = img_labelledHull[maxDist[1]] #split the shape by determining whether a point of the shape is on the right or the left of the line through the point of deepest #concavity and the middle of hullP if option == 0: img_split = splitHull(img_white, maxDepth, hullP) if option == 1: img_split = splitHull(img_labelledHull, maxDepth, hullP) #if output path specified print image of split shape if outpath != "": outimg = numpy.zeros((img_Xmax, img_Ymax, 3)) for el in img_split: X = el[0] Y = el[1] if el[2] == 1: outimg[X, Y, 0] = 255 else: outimg[X, Y, 1] = 255 imp.writeImage(outimg, outpath) return img_split
def imageNormalization(wellL, rawFolder): ''' This function makes float images integer images ''' for puits in wellL: for image in sorted(os.listdir(os.path.join(rawFolder, puits))): im = vi.readImage(os.path.join(rawFolder, puits, image)) normImage = vigra.VigraArray(im.shape, dtype=np.dtype('uint16')) normImage[:,:,0]=np.array(im[:,:,0], dtype=int) vi.writeImage(normImage,os.path.join(rawFolder, puits, image))
def crop_to_sequence(self, track_list, currSharp): ''' In the crop filename, I add the number of the image in the galerie so that they're by default ordered in time I need the bounding box of the membrane and also to use whitefield images. ''' for track in track_list: id_=track.id lstFrames=sorted(track.lstPoints.keys(), key=itemgetter(0)) rr=[]; cc=[]; val=[]; nextCoord=None for i, el in enumerate(lstFrames): im, cell_id=el coordonnees=track.lstPoints[(im, cell_id)] if nextCoord==None else nextCoord try: nextCoord=track.lstPoints[lstFrames[i+1]] except IndexError: continue else: r,c,v=draw.line_aa(coordonnees[0], coordonnees[1],nextCoord[0], nextCoord[1]) rr.extend(r); cc.extend(c); val.extend(v) for im, cell_id in lstFrames: #renumbering according to xb screen/PCNA image numbering local_im=im+1 #draw a dot on the cell which is followed cell_x, cell_y=track.lstPoints[(im, cell_id)] dot_rr, dot_cc=draw.circle(cell_x, cell_y, radius=3) image_name= self.settings.imageFilename.format(self.well, local_im) image=vi.readImage(os.path.join(self.settings.allDataFolder, self.plate, 'analyzed', self.well, 'images/tertiary_contours_expanded', image_name)) #X,x,x__, Y,y,y__=self._newImageSize(crop_coordinates) x__=self.settings.XMAX; y__=self.settings.YMAX; x=0; y=0; X=self.settings.XMAX; Y=self.settings.YMAX croppedImage = VigraArray((x__, y__, 3), dtype=np.dtype('float32')) croppedImage=image[x:X, y:Y] croppedImage[rr,cc,0]=np.array(val)*255 #If there is a sharp movement, the cell center is pinky red if im in currSharp[id_]: croppedImage[dot_rr, dot_cc, 0]=242 croppedImage[dot_rr, dot_cc, 1]=21 croppedImage[dot_rr, dot_cc, 2]=58 else: #If not, it is green croppedImage[dot_rr, dot_cc, 1]=255 vi.writeImage(croppedImage, \ os.path.join(self.outputFolder, self.plate, 'galerie', self.settings.outputImage.format(self.plate, self.well.split('_')[0],id_, im)),\ dtype=np.dtype('uint8')) return
def test_multiImageTiff(): if not 'TIFF' in im.listFormats(): return filename = 'resimage.tif' # decompose the RGB image and write the three channels as individual images # to a multi-image TIFF for i in range(3): # the first image requires mode="w" in case the image already exists im.writeImage(image2[:,:,i], filename, mode="w" if i == 0 else "a") # test different dimensions and data types im.writeImage(image, filename, mode="a") im.writeImage(image2, filename, mode="a") im.writeImage(scalar_image, filename, mode="a") # check number of images contained in the file assert(im.numberImages(filename) == 6) # check for equal data for i in range(3): img_test = im.readImage(filename, index=i) checkEqualData(img_test.dropChannelAxis(), image2[:,:,i]) checkEqualData(im.readImage(filename, index=3), image) checkEqualData(im.readImage(filename, index=4), image2) checkEqualData(im.readImage(filename, index=5).dropChannelAxis(), scalar_image)
def makeMovie(imgDir, outDir, plate, well,clef = lambda x:int(x.split('_')[2]), filtre=None, tempDir=None, offset=0): # def normWrite(img, filename): # img=(img-2**15)*(2**8-1)/(2**12-1) # vi.writeImage(img, filename) # return 1 # temp directory if tempDir is None: tempDir = os.path.join(outDir, 'temp_{}'.format(plate)) # make output directory if not os.path.isdir(outDir): os.makedirs(outDir) # movie filename movieName = 'P{}_W{}_1.avi'.format(plate, well) #checking for existence if movieName in os.listdir(outDir): print 'Done already' return if filtre == None: lstImageNames=os.listdir(imgDir) else: lstImageNames = filter(filtre, os.listdir(imgDir)) if not os.path.isdir(tempDir): os.makedirs(tempDir) f=open(os.path.join(tempDir, 'list.txt'), 'w') lstImageNames.sort(key=clef) for imageName in lstImageNames: print imageName img = vi.readImage(os.path.join(imgDir, imageName)) normImage = vigra.VigraArray(img.shape, dtype=np.dtype('uint8')) normImage[:,:,0] = (img[:,:,0]-offset)*(2**8-1)/(2**12-1) ###WARNING if you only do normImage = (img - etc then we have a flickering effect. Apparently vigra decides to do its normalization on every image as it pleases suffix = imageName.split('.')[-1] vi.writeImage(normImage, os.path.join(tempDir, os.path.basename(imageName).replace(suffix, 'jpg')), dtype = np.dtype('uint8')) f.write(os.path.join(tempDir, os.path.basename(imageName).replace(suffix, 'jpg'))+'\n') f.close() # encode command encode_command = "mencoder mf://@%s/list.txt -mf fps=3:type=jpg -o %s -ovc xvid -oac copy -xvidencopts fixed_quant=2.5" #encode_command = "mencoder mf://@list.txt -mf w=800:h=600:fps=3:type=png -ovc copy -oac copy -o %s" encode_command %= (tempDir, os.path.join(outDir, movieName)) print encode_command os.system(encode_command) # cleaning up temporary directory shell_command = 'rm %s/*' % tempDir print shell_command os.system(shell_command) return
def getPixels(image_path): if imp.isImage(image_path) == 0: print "File is not an image!" else: hull = [] image = imp.readImage(image_path) sizex = image.shape[0] sizey = image.shape[1] min_bool = False x_min, y_min = 0, 1 while y_min < sizey+1 and min_bool == False: x_min = 0 while x_min < sizex and min_bool == False: if image[x_min, -y_min, 0] != 0: min_bool = True else: x_min += 1 if min_bool == False: y_min +=1 hull.append([x_min,sizey-y_min]) result = getNext(image, hull[-1]) hull.append(result[:2]) while (hull[-1])[0] != (hull[0])[0] or (hull[-1])[1] != (hull[0])[1]: #for test in xrange(10): result = getNext(image, hull[-1], result[2]) hull.append(result[:2]) #print result #print hull[-1] #print hull img = numpy.zeros((sizex, sizey, 1)) for el in hull: img[el[0], el[1], 0] = 1 imp.writeImage(img, "test_2.jpg") #for el in hull: # el[0] += random.uniform(-0.01, 0.01) return numpy.flipud(numpy.array(hull, dtype = float))[:-1]
def makeMovieMultiChannels(imgDir, outDir,plate, well, channels=[2,1], tempDir=None, doChannel1Only=True, ranges=None,secondary = True): ''' From a list of images containing information for two channels in different images, make a movie. It is assumed that the name of a file is something like '[conditions]_--W[well]--P0001_t[frame number]_c[channel number].tif' It is not possible I think that there are more than three channels ? However it is possible to have 2 or three channels Ranges indicate how to do the normalization for the images. It should be [(min_CH1, max_CH1), (min_CH2, max_CH2)] 300714 90% [(50,750),(300,1000)] 230714 90% [(150,400),(300,1100)] ''' # movie filename movieName = 'P{}_W{}'.format(plate, well) if os.path.isdir(outDir) and movieName+'_1.avi' in os.listdir(outDir): print "Done already" return # make output directory if not os.path.isdir(outDir): os.makedirs(outDir) # temp directory if tempDir is None: tempDir = os.path.join(outDir, 'temp') if not os.path.isdir(tempDir): os.makedirs(tempDir) if len(channels)>1: lstImage={ch:filter(lambda x: 'tif' in x and int(x.split('_')[-1][1:6])==ch, os.listdir(imgDir)) for ch in channels}#os.listdir(imgDir) else: lstImage={channels[0]:os.listdir(imgDir)} #If ranges is not provided I look at the min pixel values on all channels for subsequent background substraction if ranges == None: min_={ch : 500 for ch in channels} max_ = {ch : 0 for ch in channels} for imageName in lstImage[channels[0]]: img = vi.readImage(os.path.join(imgDir, imageName)) min_[channels[0]]=min(np.min(img), min_[channels[0]]) max_[channels[0]]=max(np.max(img), max_[channels[0]]) suffix = imageName.split('_')[-1] for ch in channels[1:]: imageName2 = os.path.basename(imageName).replace(suffix, 'c{:>05}.tif'.format(ch)) if secondary: im = vi.readImage(os.path.join(imgDir, imageName2)) min_[ch]=min(np.min(im), min_[ch]) max_[ch]=max(np.max(im), max_[ch]) else: min_={ch:ranges[channels.index(ch)][0] for ch in channels} max_={ch:ranges[channels.index(ch)][1] for ch in channels} print min_, max_ if doChannel1Only: #making movie for channel 1 only (nucleus) for imageName in lstImage[channels[0]]: try: img = vi.readImage(os.path.join(imgDir, imageName)) except OSError: normImage = vigra.VigraArray(img.shape, dtype=np.dtype('uint8')) else: normImage = vigra.VigraArray(img.shape, dtype=np.dtype('uint8')) #WARNING if you only do normImage = (img - etc then we have a flickering effect. Apparently vigra decides to do its normalization on every image as it pleases im = np.array(img[:,:,0]) im[np.where(im<min_[channels[0]])]=min_[channels[0]] im[np.where(im>max_[channels[0]])]=max_[channels[0]] normImage[:,:,0] = (im-min_[channels[0]])*(2**8-1)/(max_[channels[0]]-min_[channels[0]]) #normImage[np.where(normImage>1)]=1 suffix = imageName.split('.')[-1] vi.writeImage(normImage, os.path.join(tempDir, os.path.basename(imageName).replace(suffix, 'jpg')), dtype = np.dtype('uint8')) # encode command encode_command = 'mencoder "mf://%s/*.jpg" -mf fps=3 -o %s -ovc xvid -oac copy -xvidencopts fixed_quant=2.5' encode_command %= (tempDir, os.path.join(outDir, '{}_1.avi'.format(movieName))) print encode_command os.system(encode_command) # cleaning up temporary directory shell_command = 'rm %s/*.jpg' % tempDir print shell_command os.system(shell_command) #making movie for both channels if the images exist if secondary: for imageName in lstImage[channels[0]]: try: img = vi.readImage(os.path.join(imgDir, imageName)) except OSError: colorImage = vigra.VigraArray((shape[0],shape[1], 3), dtype=np.dtype('uint8')) else: shape = img.shape colorImage = vigra.VigraArray((shape[0],shape[1], 3), dtype=np.dtype('uint8')) im = np.array(img[:,:,0]) im[np.where(im<min_[channels[0]])]=min_[channels[0]] im[np.where(im>max_[channels[0]])]=max_[channels[0]] colorImage[:,:,0] = (im-min_[channels[0]])*(2**8-1)/(max_[channels[0]]-min_[channels[0]]) suffix = imageName.split('_')[-1] for i,ch in enumerate(channels[1:]): imageName2 = os.path.basename(imageName).replace(suffix, 'c{:>05}.tif'.format(ch)) im = vi.readImage(os.path.join(imgDir, imageName2)) im = np.array(im[:,:,0]) im[np.where(im<min_[channels[ch]])]=min_[channels[ch]] im[np.where(im>max_[channels[ch]])]=max_[channels[ch]] colorImage[:,:,i+1] = (im-min_[ch])*(2**8-1)/(max_[ch]-min_[ch]) suffix = imageName.split('.')[-1] vi.writeImage(colorImage, os.path.join(tempDir, os.path.basename(imageName).replace(suffix, 'jpg')), dtype = np.dtype('uint8')) # encode command encode_command = 'mencoder "mf://%s/*.jpg" -mf fps=3 -o %s -ovc xvid -oac copy -xvidencopts fixed_quant=2.5' encode_command %= (tempDir, os.path.join(outDir, '{}_2.avi'.format(movieName))) print encode_command os.system(encode_command) # cleaning up temporary directory shell_command = 'rm %s/*.jpg' % tempDir print shell_command os.system(shell_command) return