def test_as_rgb_shape_mismatch(): np.random.seed(2323) r = np.random.randint(12, 121, size=(8, 8)) g = np.random.randint(12, 121, size=(8, 8)) b = np.random.randint(12, 121, size=(8, 6)) with pytest.raises(ValueError): mahotas.as_rgb(r, g, b)
def test_as_rgb(): np.random.seed(2323) r = np.random.random_integers(12, 120, size=(8,8)) g = np.random.random_integers(12, 120, size=(8,8)) b = np.random.random_integers(12, 120, size=(8,8)) assert mahotas.as_rgb(r,g,b).max() >= 254 assert mahotas.as_rgb(r,None,b).shape == (8,8,3) assert mahotas.as_rgb(r,None,b)[:,:,1].sum() == 0
def create_ring(self): im = self._image # This breaks up the image into RGB channels r, g, b = im.transpose(2, 0, 1) h, w = r.shape # smooth the image per channel: r12 = mh.gaussian_filter(r, 12.) g12 = mh.gaussian_filter(g, 12.) b12 = mh.gaussian_filter(b, 12.) # build back the RGB image im12 = mh.as_rgb(r12, g12, b12) X, Y = np.mgrid[:h, :w] X = X - h / 2. Y = Y - w / 2. X /= X.max() Y /= Y.max() # Array C will have the highest values in the center, fading out to the edges: C = np.exp(-2. * (X ** 2 + Y ** 2)) C -= C.min() C /= C.ptp() C = C[:, :, None] # The final result is sharp in the centre and smooths out to the borders: ring = mh.stretch(im * C + (1 - C) * im12) return ring
def composite(self, channels=('dna', 'protein', None)): import mahotas def g(ch): if ch is not None and \ self.has_channel(ch): return self.get(ch) c0,c1,c2 = channels return mahotas.as_rgb(g(c0),g(c1),g(c2))
def test_as_rgb_integer(): int_rgb = mh.as_rgb(1, 2, np.zeros((8, 6))) assert int_rgb.dtype == np.uint8 assert int_rgb.shape == (8, 6, 3) assert np.all(int_rgb[0, 0] == (1, 2, 0)) assert np.all(int_rgb[-1, 3] == (1, 2, 0)) assert np.all(int_rgb[-2, 4] == (1, 2, 0))
def test_as_rgb_integer(): int_rgb = mh.as_rgb(1,2,np.zeros((8,6))) assert int_rgb.dtype == np.uint8 assert int_rgb.shape == (8,6,3) assert np.all( int_rgb[0,0] == (1,2,0) ) assert np.all( int_rgb[-1,3] == (1,2,0) ) assert np.all( int_rgb[-2,4] == (1,2,0) )
def composite(self, plane='central'): import mahotas if plane == 'central': plane = len(self.files.values()[0])//2 def g(ch): if self.has_channel(ch): return self.get(ch, plane) return mahotas.as_rgb(g('dna'), g('protein'), None)
def makeSegmentationPicture(self,thickestPath,G,crownImg,xScale,yScale,c1x,c1y,c2x,c2y,c3x=None,c3y=None): print 'make cluster picture' crownImg=m.as_rgb(crownImg,crownImg,crownImg) vprop=G.vertex_properties["vp"] for i in thickestPath: if vprop[i]['nrOfPaths'] in c1y: y=int(vprop[i]['imgIdx'][0]) x=int(vprop[i]['imgIdx'][1]) try: crownImg[x][y]=(125,0,0) except: pass dia=vprop[i]['diameter']/(xScale/2+yScale/2) dia=dia*1.5 for j in range(int(dia)): try: crownImg[x][y+j]=(125,0,0) except: pass try: crownImg[x][y-j]=(125,0,0) except: pass try: crownImg[x-j][y]=(125,0,0) except: pass try: crownImg[x+j][y]=(125,0,0) except: pass elif vprop[i]['nrOfPaths'] in c2y: y=int(vprop[i]['imgIdx'][0]) x=int(vprop[i]['imgIdx'][1]) try: crownImg[x][y]=(125,0,0) except: pass dia=vprop[i]['diameter']/(xScale/2+yScale/2) dia=dia*1.5 for j in range(int(dia)): try: crownImg[x][y+j]=(0,125,0) except: pass try: crownImg[x][y-j]=(0,125,0) except: pass try: crownImg[x-j][y]=(0,125,0) except: pass try: crownImg[x+j][y]=(0,125,0) except: pass y=int(vprop[i]['imgIdx'][0]) x=int(vprop[i]['imgIdx'][1]) try: crownImg[x][y]=(0,0,125) except: pass dia=vprop[i]['diameter']/(xScale/2+yScale/2) dia=dia*1.5 for j in range(int(dia)): try: crownImg[x][y+j]=(0,0,125) except: pass try: crownImg[x][y-j]=(0,0,125) except: pass try: crownImg[x-j][y]=(0,0,125) except: pass try: crownImg[x+j][y]=(0,0,125) except: pass return crownImg
def composite(self, channels=('dna', 'protein', None), plane='central'): import mahotas if plane == 'central': plane = len(self.files.values()[0])//2 def g(ch): if ch is not None and self.has_channel(ch): return self.get(ch, plane) c0,c1,c2 = channels return mahotas.as_rgb(g(c0), g(c1), g(c2))
def UpdateImage(self): sigma = self.Slider_Sigma.value()/2; dilate = self.Slider_Dilate.value() if self.Combo_ImageType.currentText() == 'DAPI': if self.Check_NoisyMode.isChecked(): self.DAPI_mask = mh.dilate(self.img_array > self.T_mean, np.ones((dilate, dilate))); self.gaussian_f = mh.gaussian_filter(self.img_array.astype('int'), sigma) else: self.gaussian_f = mh.gaussian_filter(self.img_array.astype('float'), sigma) self.DAPI_mask = mh.dilate(self.gaussian_f > self.gaussian_f.mean(), np.ones((dilate, dilate))); if self.Check_SingleColor.isChecked(): self.im_axes.imshow(mh.as_rgb(0, 0, self.DAPI_mask)); else: plt.imshow(mh.as_rgb(np.maximum(self.img_array,self.gaussian_f), self.gaussian_f, self.gaussian_f > self.T_otsu)) self.ClusterMap.setupUi(figure=self.im_figure, title='Image Display', xlabel='pixels (x)', ylabel='pixels(y)') self.Button_SNR.setEnabled(False); self.Check_TissueMaxima.setEnabled(False); self.DAPI_set_bool = True self.Text_Log.append('>Updated image; DAPI; sigma=%.1f,dilate=%d\n' % (sigma, dilate)) elif self.Combo_ImageType.currentText() == 'Fluorescence (Signal)': self.gaussian_f = mh.gaussian_filter(self.img_array.astype('float'), sigma) self.gT_mean = self.gaussian_f.mean() all_maximas = mh.regmax(self.gaussian_f) self.all_maximas = mh.dilate(all_maximas, np.ones((dilate, dilate))) if self.Check_TissueMaxima.isChecked(): self.tissue_maxima = self.all_maximas*self.Tissue_Mask self.im_axes.imshow(mh.as_rgb( np.maximum(255*self.tissue_maxima, self.gaussian_f), self.gaussian_f, self.img_array > self.gT_mean)) else: self.im_axes.imshow(mh.as_rgb( np.maximum(255*self.all_maximas, self.gaussian_f), self.gaussian_f, self.img_array > self.gT_mean)) self.ClusterMap.setupUi(figure=self.im_figure, title='Image Display', xlabel='pixels (x)', ylabel='pixels(y)') self.Text_Log.append('>Updated image; Mode: Fluor; sigma=%.1f,dilate=%d\n' % (sigma, dilate)) if self.DAPI_set_bool: self.Button_SNR.setEnabled(True); self.Check_TissueMaxima.setEnabled(True)
def overlay(input_image,seg_mask,frame_num,sizeX,sizeY): import mahotas as mh cmap = plt.get_cmap('gray') seg_mask=seg_mask>0 cmap_2_use = truncate_colormap(cmap,0.9,1) border2overlay = np.ma.masked_where(seg_mask ==0, seg_mask) x =mh.as_rgb(input_image[frame_num][0,:,:],input_image[frame_num][1,:,:],np.zeros((sizeY,sizeX))) x[:,:,1][x[:,:,1]>240]=240 x[:,:,0][x[:,:,0]>240]=240 slice2show = [slice(0,sizeY),slice(0,sizeX)] plt.imshow(x[slice2show]/np.array([240.,240.,1]).reshape(1,1,3)) plt.imshow(border2overlay[slice2show],cmap_2_use,alpha=0.4),plt.axis('off')
def overlay(input_image, seg_mask, frame_num, sizeX, sizeY): import mahotas as mh cmap = plt.get_cmap('gray') seg_mask = seg_mask > 0 cmap_2_use = truncate_colormap(cmap, 0.9, 1) border2overlay = np.ma.masked_where(seg_mask == 0, seg_mask) x = mh.as_rgb(input_image[frame_num][0, :, :], input_image[frame_num][1, :, :], np.zeros((sizeY, sizeX))) x[:, :, 1][x[:, :, 1] > 240] = 240 x[:, :, 0][x[:, :, 0] > 240] = 240 slice2show = [slice(0, sizeY), slice(0, sizeX)] plt.imshow(x[slice2show] / np.array([240., 240., 1]).reshape(1, 1, 3)) plt.imshow(border2overlay[slice2show], cmap_2_use, alpha=0.4), plt.axis('off')
def show_segmentation_boundaries(input_image,seg_mask,frame_num,sizeX,sizeY): import mahotas as mh cmap = plt.get_cmap('gray') #outlines dsk = mh.disk(7) boundaries = mh.dilate(seg_mask,dsk)-seg_mask boundaries=boundaries>0 cmap_2_use = truncate_colormap(cmap,0.9,1) border2overlay = np.ma.masked_where(boundaries ==0, boundaries) x =mh.as_rgb(input_image[frame_num][0,:,:],input_image[frame_num][1,:,:],np.zeros((sizeY,sizeX))) x[:,:,1][x[:,:,1]>240]=240 x[:,:,0][x[:,:,0]>240]=240 slice2show = [slice(0,sizeY),slice(0,sizeX)] plt.imshow(x[slice2show]/np.array([240.,240.,1]).reshape(1,1,3)) plt.imshow(border2overlay[slice2show],cmap_2_use,alpha=0.8),plt.axis('off')
def composite(dna, protein, rois): '''Build composite image Parameters ---------- dna : ndarray protein : ndarray rois : ndarray Returns ------- comp : ndarray of shape (h,w,3) RGB image ''' borders = 255*mh.borders(rois != 0) borders = np.dstack([borders, borders, borders]) im = np.maximum(borders, mh.as_rgb(dna, protein, 0)).astype(np.uint8) im[492:500,400:400+50/MU_PER_PIXEL] = 255 return im
def composite(dna, protein, rois): '''Build composite image Parameters ---------- dna : ndarray protein : ndarray rois : ndarray Returns ------- comp : ndarray of shape (h,w,3) RGB image ''' borders = 255 * mh.borders(rois != 0) borders = np.dstack([borders, borders, borders]) im = np.maximum(borders, mh.as_rgb(dna, protein, 0)).astype(np.uint8) im[492:500, 400:400 + 50 / MU_PER_PIXEL] = 255 return im
def center_focus(im,f): r, g, b = im.transpose(2,0,1) r12 = mh.gaussian_filter(r, 12.0) g12 = mh.gaussian_filter(g, 12.0) b12 = mh.gaussian_filter(b, 12.0) im12 = mh.as_rgb(r12,g12,b12) h, w = r.shape Y, X = np.mgrid[:h,:w] Y = Y-h/2.0 Y = Y/Y.max() X = X-w/2.0 X = X/X.max() W = np.exp(-2.0*(X**2 + Y**2)/0.5) W = W - W.min() W = W/W.ptp() W = W[:, :, None] ringed = mh.stretch(im*W + (1.0-W)*im12) plt.imshow(ringed) plt.savefig(f) plt.show ()
def show_segmentation_boundaries(input_image, seg_mask, frame_num, sizeX, sizeY): import mahotas as mh cmap = plt.get_cmap('gray') #outlines dsk = mh.disk(7) boundaries = mh.dilate(seg_mask, dsk) - seg_mask boundaries = boundaries > 0 cmap_2_use = truncate_colormap(cmap, 0.9, 1) border2overlay = np.ma.masked_where(boundaries == 0, boundaries) x = mh.as_rgb(input_image[frame_num][0, :, :], input_image[frame_num][1, :, :], np.zeros((sizeY, sizeX))) x[:, :, 1][x[:, :, 1] > 240] = 240 x[:, :, 0][x[:, :, 0] > 240] = 240 slice2show = [slice(0, sizeY), slice(0, sizeX)] plt.imshow(x[slice2show] / np.array([240., 240., 1]).reshape(1, 1, 3)) plt.imshow(border2overlay[slice2show], cmap_2_use, alpha=0.8), plt.axis('off')
import numpy as np # Read in the image im = mh.imread('lenna.jpg') # This breaks up the image into RGB channels r, g, b = im.transpose(2, 0, 1) h, w = r.shape # smooth the image per channel: r12 = mh.gaussian_filter(r, 12.) g12 = mh.gaussian_filter(g, 12.) b12 = mh.gaussian_filter(b, 12.) # build back the RGB image im12 = mh.as_rgb(r12, g12, b12) X, Y = np.mgrid[:h, :w] X = X - h / 2. Y = Y - w / 2. X /= X.max() Y /= Y.max() # Array C will have the highest values in the center, fading out to the edges: C = np.exp(-2. * (X**2 + Y**2)) C -= C.min() C /= C.ptp() C = C[:, :, None] # The final result is sharp in the centre and smooths out to the borders:
def test_as_rgb_Nones(): with pytest.raises(ValueError): mahotas.as_rgb(None, None, None)
import mahotas as mh import numpy as np im = mh.imread('lenna.jpg') r,g,b = im.transpose(2,0,1) h,w = r.shape r12 = mh.gaussian_filter(r, 12.) g12 = mh.gaussian_filter(g, 12.) b12 = mh.gaussian_filter(b, 12.) im12 = mh.as_rgb(r12,g12,b12) X,Y = np.mgrid[:h,:w] X = X-h/2. Y = Y-w/2. X /= X.max() Y /= Y.max() C = np.exp(-2.*(X**2+ Y**2)) C -= C.min() C /= C.ptp() C = C[:,:,None] ring = mh.stretch(im*C + (1-C)*im12) mh.imsave('lenna-ring.jpg', ring)
mask = initImage[:, :, 1] > (val * .8) # set init green channel to random noise initImage[:, :, 0] = img_noise[:, :, 0] if localizationClass == 0: plt.subplot(numFigs, 3, 1) plt.imshow(initImage[:, :, 0], 'gray') plt.title('green_init') plt.axis('off') plt.subplot(numFigs, 3, 2) plt.imshow(initImage[:, :, 1], 'gray') plt.title('red_init') plt.axis('off') plt.subplot(numFigs, 3, 3) plt.imshow(mh.as_rgb(initImage0[:, :, 1], initImage0[:, :, 0], None)) plt.title('original') plt.axis('off') #plt.savefig('./output_figures/'+localizationTerms[class2sample_from]+'_'+str(curInd)+'_init.png') generatedCell = render_naive_gaussian_blur_l2_clamped( lastAct[:, localizationClass], mask=mask, clip_val_g=[useTopPerc[localizationTerms[localizationClass]]], img0=initImage, iter_n=100, step=.3, sigma=.7, decay=.009) plt.subplot(numFigs, 3, (localizationClass + 1) * 3 + 1)
def makeSegmentationPicture(self, thickestPath, G, crownImg, xScale, yScale, c1x, c1y, c2x, c2y, c3x=None, c3y=None): print 'make cluster picture' crownImg = m.as_rgb(crownImg, crownImg, crownImg) vprop = G.vertex_properties["vp"] for i in thickestPath: if vprop[i]['nrOfPaths'] in c1y: y = int(vprop[i]['imgIdx'][0]) x = int(vprop[i]['imgIdx'][1]) try: crownImg[x][y] = (125, 0, 0) except: pass dia = vprop[i]['diameter'] / (xScale / 2 + yScale / 2) dia = dia * 1.5 for j in range(int(dia)): try: crownImg[x][y + j] = (125, 0, 0) except: pass try: crownImg[x][y - j] = (125, 0, 0) except: pass try: crownImg[x - j][y] = (125, 0, 0) except: pass try: crownImg[x + j][y] = (125, 0, 0) except: pass elif vprop[i]['nrOfPaths'] in c2y: y = int(vprop[i]['imgIdx'][0]) x = int(vprop[i]['imgIdx'][1]) try: crownImg[x][y] = (125, 0, 0) except: pass dia = vprop[i]['diameter'] / (xScale / 2 + yScale / 2) dia = dia * 1.5 for j in range(int(dia)): try: crownImg[x][y + j] = (0, 125, 0) except: pass try: crownImg[x][y - j] = (0, 125, 0) except: pass try: crownImg[x - j][y] = (0, 125, 0) except: pass try: crownImg[x + j][y] = (0, 125, 0) except: pass y = int(vprop[i]['imgIdx'][0]) x = int(vprop[i]['imgIdx'][1]) try: crownImg[x][y] = (0, 0, 125) except: pass dia = vprop[i]['diameter'] / (xScale / 2 + yScale / 2) dia = dia * 1.5 for j in range(int(dia)): try: crownImg[x][y + j] = (0, 0, 125) except: pass try: crownImg[x][y - j] = (0, 0, 125) except: pass try: crownImg[x - j][y] = (0, 0, 125) except: pass try: crownImg[x + j][y] = (0, 0, 125) except: pass return crownImg
def check_sigma(sigma): dnaf = mh.gaussian_filter(dna.astype(float), sigma) maxima = mh.regmax(mh.stretch(dnaf)) maxima = mh.dilate(maxima, np.ones((5,5))) plt.imshow(mh.as_rgb(np.maximum(255*maxima, dnaf), dnaf, dna > T_mean))
def test_as_rgb_Nones(): mahotas.as_rgb(None,None,None)
def createOverlayImage(image, label): red = np.copy(image) red[np.nonzero(label)] = 255 greenAndBlue = np.copy(image) greenAndBlue[np.nonzero(label)] = 0 return mahotas.as_rgb(red, greenAndBlue, greenAndBlue)
def false_color(base,n0,n1): g = mh.imread(basedir+'{}/{:02}-{:03}-protein.tiff'.format(base,n0,n1)) r = mh.imread(basedir+'{}/{:02}-{:03}-dna.tiff'.format(base,n0,n1)) return mh.as_rgb(r,g,None)
def test_as_rgb_shape_mismatch(): np.random.seed(2323) r = np.random.random_integers(12, 120, size=(8,8)) g = np.random.random_integers(12, 120, size=(8,8)) b = np.random.random_integers(12, 120, size=(8,6)) mahotas.as_rgb(r,g,b)
import numpy as np import mahotas as mh canvas = np.zeros((384,256),np.uint8) for y in xrange(512): for x in xrange(512): if (x-128)**2+1.8*(y-64)**2 < 61*64: canvas[y,x] = 4 if (x-128)**2+1.8*(y-64)**2 < 61*60: canvas[y,x] = 1 if (x-128)**2+1.8*(y-192)**2 < 61*64: canvas[y,x] = 2 if (x-128)**2+1.8*(y-320)**2 < 61*60: canvas[y,x] = 3 for y in xrange(-21,21): for x in xrange(-21,21): if x**2 + y**2 < 14*14: canvas[332+y,62+x] = 3 r,g,b = (canvas == 1), (canvas == 2), (canvas == 3) mh.imsave('2013-09-16.png',mh.as_rgb(r,g,b))