def local_contrast_normalization(img, selem=disk(5)): img = (img * 255).astype(np.uint8) if len(img.shape) <= 2: img = rank.equalize(img, selem) else: img = np.asarray([rank.equalize(ch, selem) for ch in img]) img = img.astype(np.float32) / 255 return img
def ref_region( img: np.ndarray, selem: Any = disk(5), sigma: int = 3, opening_se: np.ndarray = np.ones((10, 10)), closing_se: np.ndarray = np.ones((5, 5)), verbose: bool = False ): """ """ # Perform histogram equalisation : _img_eq = rank.equalize(img, selem=selem) # Perform edge detection : _edges = canny(_img_eq, sigma=3) _filled = ndi.binary_fill_holes(_edges) # Morphological processing : _eroded = utils.closing( utils.opening(np.float64(_filled), opening_se), closing_se ) if verbose: utils.side_by_side(img, _img_eq, title1="Original", title2="Histogram Equalised") #plt.title('Lol') utils.side_by_side(_img_eq, _filled, title1="Histogram Equalised", title2="Canny Edge Detection + Filled image") #plt.title('Lal') utils.side_by_side(_filled, _eroded, title1="Canny Edge Detection + Filled image", title2="Opening, closing") #plt.title('Lel') return _eroded
def localHistEqualization(image, radius, output): """ Make a local histogram stretch using a moving window. :param str image: Input image. :param int radius: Window radius. 1 for a 3x3 window, 2 for 5x5, ... :param str output: Output image (will be the same format and data type as the input image). :return: -- """ ds = gdal.Open(image, gdal.GA_ReadOnly) drv = ds.GetDriver() cols = ds.RasterXSize rows = ds.RasterYSize bands = ds.RasterCount if os.path.exists(output): os.remove(output) out_ds = drv.Create(output, cols, rows, bands, ds.GetRasterBand(1).DataType) out_ds.SetGeoTransform(ds.GetGeoTransform()) out_ds.SetProjection(ds.GetProjection()) if not ds.GetProjection(): warnings.warn('Warning: Input image seems to have no geo-information! Output image will not be geo-referenced!') print 'Applying local histogram stretch to image {img}, containing {n} bands'.format(img=image, n=bands) print 'Working on band' for b in range(bands): print '\t...', b + 1 data = ds.GetRasterBand(b + 1).ReadAsArray() stretched = rank.equalize(data, selem=disk(radius)) out_ds.GetRasterBand(b + 1).WriteArray(stretched) out_ds = None ds = None return True
def preprocess(dcm_img): '''Take the DICOM file and convert it to a numpy array''' # generate a numpy array with range 0-1 pixel intensities img = dcm_img.pixel_array.astype(float) / np.max(dcm_img.pixel_array) # some images have height < width. #in this case, rotate counter-clockwise so all images have same orientation if img.shape[0] < img.shape[1]: img = np.rot90(img) # crop a square image from the center img = crop(img) # scale the image by the pixel spacing given in the DICOM file img = rescale(img, dcm_img) # resize the image based on given number of pixels img = transform.resize(img, (NUM_PIXELS, NUM_PIXELS)) # optionally denoise the image #img = denoise_tv_chambolle(img, weight=0.05, multichannel=False) # enhance the contrast of the image to make regions more distinct selem = disk(30) img = rank.equalize(img, selem=selem) img = img_as_ubyte(img) # converts 0-1 range to 0-255 range img = exposure.rescale_intensity(img) return img
def local_equalize(imgfiles): patch_kw = dict(patch_size=5, # 5x5 patches patch_distance=6, # 13x13 search area multichannel=True) for imgfile in imgfiles: img = skimage.io.imread(imgfile) # estimate the noise standard deviation from the noisy image sigma_est = np.mean(estimate_sigma(img, multichannel=True)) print("estimated noise standard deviation = {}".format(sigma_est)) fig, ax = plt.subplots(nrows=1, ncols=3, figsize=(8, 6), sharex=True, sharey=True, subplot_kw={'adjustable': 'box-forced'}) # Equalization selem = disk(30) img_eq = rank.equalize(img, selem=selem) # slow algorithm denoise = denoise_nl_means(img_eq, h=1.15 * sigma_est, fast_mode=False, **patch_kw) ax[0].imshow(img, cmap='gray') ax[0].axis('off') ax[0].set_title('noisy') ax[1].imshow(denoise, cmap='gray') ax[1].axis('off') ax[1].set_title('non-local means\n(slow)') ax[2].imshow(img_eq, cmap='gray') ax[2].axis('off') ax[2].set_title('local equalize') fig.tight_layout() plt.show()
def Binary(self, img): if self.blocksize % 2 == 0: self.blocksize += 1 if self.threshold_mode == ThresholdMode.Const: #__, img = cv2.threshold(img, self.constant, 255, cv2.THRESH_BINARY) img = rank.equalize(img, selem=disk(self.constant)) elif self.threshold_mode == ThresholdMode.Otsu: #img = cv2.GaussianBlur(img, (5,5), 0) threshold, imgblur = cv2.threshold( img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) logging.info("Threshold value is {}".format(threshold)) __, img = cv2.threshold(img, threshold, 255, cv2.THRESH_BINARY) elif self.threshold_mode == ThresholdMode.Mean: img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, self.blocksize, self.constant) elif self.threshold_mode == ThresholdMode.Gauss: img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, self.blocksize, self.constant) return img
def Equalizer(file): ''' Equalizes image spectrum (in gray scale) ''' img = io.imread(file, as_grey=True) selem = disk(100) img_eq = rank.equalize(img, selem=selem) return img_eq
def equalizeHist(image, globalHist=False): if globalHist: img = exposure.equalize_hist(image) else: # Equalization selem = disk(200) img = rank.equalize(image, selem=selem) return img
def local_normalize(im): width, _ = im.shape disksize = int(width / 5) if disksize % 2 == 0: disksize = disksize + 1 selem = disk(disksize) im = rank.equalize(im, selem=selem) return im
def histogramEqualization(self, image): """ Fourth step preprocessing : Apply local histogram equalization to grayscale images """ kernel = morp.disk(30) newImage = rank.equalize(image, selem=kernel) return newImage
def local_normalize(im): norm = img_as_ubyte(normalize(im)) # TODO: mainly using this as a type conversion, but it's expensive width, _ = im.shape disksize = int(width/5) if disksize % 2 == 0: disksize = disksize + 1 selem = disk(disksize) norm2 = rank.equalize(norm, selem=selem) return norm2
def local_histo_equalize(image): """ Apply local histogram equalization to grayscale images. Parameters: image: A grayscale image. """ kernel = morp.disk(30) img_local = rank.equalize(image, selem=kernel) return img_local
def _equalize(self, sample): sample_ubyte = img_as_ubyte(sample) if self.selem is None: sample_eq = exposure.equalize_hist(sample_ubyte) else: sample_eq = rank.equalize(sample_ubyte, selem=self.selem) return sample_eq
def preprocess(img): gray_image = rgb2gray(img) cropped = crop(gray_image, ((50, 50), (50, 50)), copy=False) equalized_image = rank.equalize(cropped, selem=disk(5)) blur = gaussian(equalized_image, sigma=1.4) binary = np.where(blur > np.mean(blur), 1.0, 0.0) skeleton = skeletonize(binary) skeleton = invert(skeleton) return (skeleton, gray_image)
def get_canny_edge_image(image, radius, sigma): """ Compute Canny edge image """ # local histogram equalization grayscale = equalize(image, selem=disk(radius)) try: return canny(grayscale, sigma=sigma) except TypeError: print("Canny type error") return np.zeros(image.shape)
def local_histogram_equalization(img, disk_size): if len(img.shape) == 2: kernel = morphology.rectangle(disk_size, disk_size) equalized_img = rank.equalize(img, kernel) return equalized_img bgr = cv2.split(img) equalized_channels = tuple( local_histogram_equalization(x, disk_size) for x in bgr) equalized_img = np.dstack(equalized_channels) return equalized_img
def check_all(): selem = morphology.disk(1) refs = np.load( os.path.join(skimage.data_dir, "rank_filter_tests.npz")) assert_equal(refs["autolevel"], rank.autolevel(self.image, selem)) assert_equal(refs["autolevel_percentile"], rank.autolevel_percentile(self.image, selem)) assert_equal(refs["bottomhat"], rank.bottomhat(self.image, selem)) assert_equal(refs["equalize"], rank.equalize(self.image, selem)) assert_equal(refs["gradient"], rank.gradient(self.image, selem)) assert_equal(refs["gradient_percentile"], rank.gradient_percentile(self.image, selem)) assert_equal(refs["maximum"], rank.maximum(self.image, selem)) assert_equal(refs["mean"], rank.mean(self.image, selem)) assert_equal(refs["geometric_mean"], rank.geometric_mean(self.image, selem)), assert_equal(refs["mean_percentile"], rank.mean_percentile(self.image, selem)) assert_equal(refs["mean_bilateral"], rank.mean_bilateral(self.image, selem)) assert_equal(refs["subtract_mean"], rank.subtract_mean(self.image, selem)) assert_equal(refs["subtract_mean_percentile"], rank.subtract_mean_percentile(self.image, selem)) assert_equal(refs["median"], rank.median(self.image, selem)) assert_equal(refs["minimum"], rank.minimum(self.image, selem)) assert_equal(refs["modal"], rank.modal(self.image, selem)) assert_equal(refs["enhance_contrast"], rank.enhance_contrast(self.image, selem)) assert_equal(refs["enhance_contrast_percentile"], rank.enhance_contrast_percentile(self.image, selem)) assert_equal(refs["pop"], rank.pop(self.image, selem)) assert_equal(refs["pop_percentile"], rank.pop_percentile(self.image, selem)) assert_equal(refs["pop_bilateral"], rank.pop_bilateral(self.image, selem)) assert_equal(refs["sum"], rank.sum(self.image, selem)) assert_equal(refs["sum_bilateral"], rank.sum_bilateral(self.image, selem)) assert_equal(refs["sum_percentile"], rank.sum_percentile(self.image, selem)) assert_equal(refs["threshold"], rank.threshold(self.image, selem)) assert_equal(refs["threshold_percentile"], rank.threshold_percentile(self.image, selem)) assert_equal(refs["tophat"], rank.tophat(self.image, selem)) assert_equal(refs["noise_filter"], rank.noise_filter(self.image, selem)) assert_equal(refs["entropy"], rank.entropy(self.image, selem)) assert_equal(refs["otsu"], rank.otsu(self.image, selem)) assert_equal(refs["percentile"], rank.percentile(self.image, selem)) assert_equal(refs["windowed_histogram"], rank.windowed_histogram(self.image, selem))
def ImageEnhancement(normalized_iris): row = 64 col = 512 normalized_iris = normalized_iris.astype(np.uint8) enhanced_image = normalized_iris enhanced_image = equalize(enhanced_image, disk(32)) roi = enhanced_image[0:48, :] return roi
def find_match(img, template): img_eq = rank.equalize(img, selem=disk(100)) # res = cross_filter(img_eq, template) res = cv2.matchTemplate(img_eq, template, cv2.TM_CCORR_NORMED) i_off = (img.shape[0] - res.shape[0]) / 2 j_off = (img.shape[1] - res.shape[1]) / 2 minval, _, minloc, _ = cv2.minMaxLoc(res) # maxj, maxi = maxloc minj, mini = minloc sp_delx, sp_dely = get_subpixel(res) # sp_delx, sp_dely = 0, 0 return res, mini + i_off + sp_dely, minj + j_off + sp_delx
def enhance_img(img): """actually, the enhance method is based on another Ma Li's paper. 'Iris Recognition Based on Multichannel Gabor Filtering' :param img: the input img :return: the enhanced image :rtype: ndarray """ kernel = morp.disk(32) img_local = rank.equalize(img.astype(np.uint8), selem=kernel) enhanced = cv2.GaussianBlur(img_local, (5, 5), 0) return enhanced
def rescale(initial_data, log_scale=True, method='adaptive_equalization'): norm = (initial_data-initial_data.min())/initial_data.max() exponent = 1000 log = np.log(exponent*norm+1)/np.log(exponent) if log_scale else norm if method == 'adaptive_equalization': return exposure.equalize_adapthist(log/log.max(), nbins=2048, kernel_size=64) elif method == 'adjust_sigmoid': return exposure.adjust_sigmoid(log/log.max(), cutoff=0.5, gain=20) elif method == 'global_equalization': return exposure.equalize_hist(log / log.max(), nbins=1024) elif method == 'local_equalization': return rank.equalize(log / log.max(), selem=disk(30 )) return
def get_canny_edge_image(image: Array, mask: Optional[Array], radius=30, sigma=0.5): """Compute Canny edge image.""" from skimage.filters.rank import equalize from skimage.morphology import disk from skimage.feature import canny inverse_mask = ~mask result = equalize(image, selem=disk(radius), mask=inverse_mask) result = canny(result, sigma=sigma, mask=inverse_mask) return np.ma.array(result, mask=mask)
def ImageEnhancement(normalized_iris): row = 64 col = 512 normalized_iris = normalized_iris.astype(np.uint8) enhanced_image = normalized_iris enhanced_image = equalize(enhanced_image, disk(32)) roi = enhanced_image[0:48, :] #cv2.imshow('enh',roi) #cv2.waitKey(0) return roi
def test_histogram_equalization_methods(image): images = {} img_gray = rgb2gray(image) images['grayscale'] = img_gray global_eq = exposure.equalize_hist(img_gray) images['global'] = global_eq selem = disk(30) local_eq = rank.equalize(img_gray, selem=selem) images['local'] = local_eq plot_images(images, 2, 3, cmap='gray')
def localEqualization(picture, window): fig = plt.figure(figsize=(8, 5)) axes = np.zeros((2, 4), dtype=np.object) axes[0, 0] = fig.add_subplot(2, 4, 1) img_local = rank.equalize(picture, selem=window) for i in range(1, 4): axes[0, i] = fig.add_subplot(2, 4, 1 + i, sharex=axes[0, 0], sharey=axes[0, 0]) for i in range(0, 4): axes[1, i] = fig.add_subplot(2, 4, 5 + i) return img_local
def computeExtImage2(img): img=plt.imread('images/img1.png') img=img[:,:,0] showImg(img,text='original') p2, p98 = np.percentile(img, (2, 98)) img_rescale = exposure.rescale_intensity(img, in_range=(p2, p98)) showImg(img_rescale,text='rescaled') selem=np.ones([50,50],dtype=np.uint8) img_eq = rank.equalize(img, selem=selem) img_eq=img_eq/255.0 showImg(img_eq,text='histeq') return img_eq
def _exposure(img, method='adapt', intensity=-1, debug=False): """ preprocess image mostly by renormalization method: contrast, equalization, adapt, gamma, sigmoid """ import skimage.exposure # histogram filter if method == 'contrast': if debug: print('... contrast histogram') if 0 < intensity < 49: p2_f, p98_f = intensity, 100 - intensity else: p2_f, p98_f = 2, 98 p2, p98 = np.percentile(img, (p2_f, p98_f)) U = skimage.exposure.rescale_intensity(img, in_range=(p2, p98)) elif method == 'equalization': if debug: print('... global equalize') U = skimage.exposure.equalize_hist(img) elif method == 'adapt': if debug: print('... contrast limited adaptive histogram equalization (CLAHE)') if intensity == -1: intensity = int(img.shape[0]/8) U = skimage.exposure.equalize_adapthist(_rescale_to_dtype(img, 'uint16'), kernel_size=intensity, clip_limit=0.03) elif method == 'local': if debug: print('... local histogram equalization') if intensity == -1: intensity = 30 from skimage.morphology import disk from skimage.filters import rank selem = disk(intensity) U = rank.equalize(_rescale_to_dtype(img, 'uint8'), selem=selem) elif method == 'gamma': if debug: print('... gamma equalize') if intensity == -1: intensity = 0.80 U = skimage.exposure.adjust_gamma(img, gamma=intensity) elif method == 'sigmoid': if debug: print('... sigmoid equalize') if intensity == -1: intensity = 0.5 U = skimage.exposure.adjust_sigmoid(img, cutoff=intensity) else: print(_operation_list("exposure")) U = img if skimage.exposure.is_low_contrast(U): print('... low contrast image') return pims.Frame(U)
def get_canny_edge_image(image: Image, radius=30, sigma=0.5): """Compute Canny edge image.""" logger.debug("Computing Canny edge image") # local histogram equalization gray_ubyte = image['gray_ubyte'] mask = gray_ubyte.mask inverse_mask = ~mask result = equalize(gray_ubyte.data, selem=disk(radius), mask=inverse_mask) try: result = canny(result, sigma=sigma, mask=inverse_mask) except TypeError: logger.warning("Canny type error") result[:] = 0 logger.debug("Done computing Canny edge image") return np.ma.array(result, mask=mask)
def Aug(img): img_np = img[0].numpy() del img # inputs_np = exposure.equalize_hist(img_np, clip_limit=0.03) selem = disk(1) inputs_np = rank.equalize(img_np, selem=selem) inputs = torch.Tensor(inputs_np).reshape(1, 256, 256) del inputs_np A = torch.Tensor() A = torch.cat((A, inputs)) A = torch.cat((A, inputs)) A = torch.cat((A, inputs)) return A
def equalize_histogram(image): images = {} img_gray = image if (len(img_gray.shape) > 2): img_gray = rgb2gray(image) images['grayscale'] = img_gray global_eq = exposure.equalize_hist(img_gray) images['global'] = global_eq local_eq = rank.equalize(img_gray, selem=disk(30)) images['local'] = local_eq plot_images(images, 2, 3, cmap='gray') return local_eq
def computeExtImage(img): #rescale p2, p98 = np.percentile(img, (2, 98)) img_rescale = exposure.rescale_intensity(img, in_range=(p2, p98)) #hist eq selem=np.ones([20,5],dtype=np.uint8) img_eq = rank.equalize(img, selem=selem) img_eq=img_eq/255.0 img_eq_smooth=gaussian_filter(img_eq,sigma=2,order=0) img_smooth=gaussian_filter(img,sigma=2,order=0) gy,gx=np.gradient(img_smooth) wi=2.0; weq=1.0; wed=25.0; result=wi*img_rescale+weq*img_eq_smooth+wed*gy res=gaussian_filter(result,sigma=2.0,order=0) res_rescaled=rescaleImage(res) return res_rescaled
def check_all(): np.random.seed(0) image = np.random.rand(25, 25) selem = morphology.disk(1) refs = np.load(os.path.join(skimage.data_dir, "rank_filter_tests.npz")) assert_equal(refs["autolevel"], rank.autolevel(image, selem)) assert_equal(refs["autolevel_percentile"], rank.autolevel_percentile(image, selem)) assert_equal(refs["bottomhat"], rank.bottomhat(image, selem)) assert_equal(refs["equalize"], rank.equalize(image, selem)) assert_equal(refs["gradient"], rank.gradient(image, selem)) assert_equal(refs["gradient_percentile"], rank.gradient_percentile(image, selem)) assert_equal(refs["maximum"], rank.maximum(image, selem)) assert_equal(refs["mean"], rank.mean(image, selem)) assert_equal(refs["mean_percentile"], rank.mean_percentile(image, selem)) assert_equal(refs["mean_bilateral"], rank.mean_bilateral(image, selem)) assert_equal(refs["subtract_mean"], rank.subtract_mean(image, selem)) assert_equal(refs["subtract_mean_percentile"], rank.subtract_mean_percentile(image, selem)) assert_equal(refs["median"], rank.median(image, selem)) assert_equal(refs["minimum"], rank.minimum(image, selem)) assert_equal(refs["modal"], rank.modal(image, selem)) assert_equal(refs["enhance_contrast"], rank.enhance_contrast(image, selem)) assert_equal(refs["enhance_contrast_percentile"], rank.enhance_contrast_percentile(image, selem)) assert_equal(refs["pop"], rank.pop(image, selem)) assert_equal(refs["pop_percentile"], rank.pop_percentile(image, selem)) assert_equal(refs["pop_bilateral"], rank.pop_bilateral(image, selem)) assert_equal(refs["sum"], rank.sum(image, selem)) assert_equal(refs["sum_bilateral"], rank.sum_bilateral(image, selem)) assert_equal(refs["sum_percentile"], rank.sum_percentile(image, selem)) assert_equal(refs["threshold"], rank.threshold(image, selem)) assert_equal(refs["threshold_percentile"], rank.threshold_percentile(image, selem)) assert_equal(refs["tophat"], rank.tophat(image, selem)) assert_equal(refs["noise_filter"], rank.noise_filter(image, selem)) assert_equal(refs["entropy"], rank.entropy(image, selem)) assert_equal(refs["otsu"], rank.otsu(image, selem)) assert_equal(refs["percentile"], rank.percentile(image, selem)) assert_equal(refs["windowed_histogram"], rank.windowed_histogram(image, selem))
def main(): parser = optparse.OptionParser() parser.add_option('-i', '--image', type=str, default='empty_dewar/puck4_five_missing.jpg', help='Specify the image') parser.add_option('-c', '--combine', type=int, default=1, help='Specify the number of images to combine') options, args = parser.parse_args() if options.combine == 1: original_image = img_as_float(imread(options.image)) else: original_image = img_as_float(combine(options.image, length=options.combine)) fig, axes = plt.subplots(3, 4) a = axes[0, 0] a.imshow(original_image) a.set_title('original image') selem = disk(30) gray_image = color.rgb2gray(original_image) b = axes[0, 1] b.imshow(gray_image, cmap='gray') b.set_title('gray image') img_rank = rank.equalize(gray_image, selem=selem) c = axes[0, 2] c.imshow(img_rank, cmap='gray') c.set_title('rank equalized image') edges = canny(img_rank, sigma=5) #img_med = median(gray_image, selem=selem) d = axes[0, 3] d.imshow(edges, cmap='gray') d.set_title('edges from rank equalized') e = axes[1, 0] img_sharp = unsharp(gray_image) img_sharp = img_sharp/float(img_sharp.max()) e.imshow(img_sharp, cmap='gray') imsave('img_sharp.jpg', img_sharp) e.set_title('unsharp') f = axes[1, 1] edges = canny(img_sharp, sigma=7.0, low_threshold=0.04, high_threshold=0.05) f.imshow(gaussian(edges, 3), cmap='gray') f.set_title('edges from unsharp image sigma=7') g = axes[1, 2] edges = canny(img_sharp, sigma=2.0, low_threshold=0.04, high_threshold=0.05) g.imshow(gaussian(edges, 3), cmap='gray') g.set_title('edges from unsharp image sigma=2') h = axes[1, 3] edges = canny(img_sharp, sigma=3.0, low_threshold=0.04, high_threshold=0.05) h.imshow(gaussian(edges, 3), cmap='gray') h.set_title('edges from unsharp image sigma=3') i = axes[2, 0] edges = canny(img_sharp, sigma=4.0, low_threshold=0.04, high_threshold=0.05) i.imshow(gaussian(edges, 3), cmap='gray') i.set_title('edges from unsharp image sigma=4') #j = axes[2, 1] #j.imshow(gaussian(img_sharp, sigma=4), cmap='gray') #j.set_title('gaussian on unsharp sigma=4') imsave('edges.jpg', img_as_int(edges)) print edges #j = axes[2, 1] #result = hough_ellipse(edges, min_size=20, max_size=100) #result.sort(order='accumulator', reverse=True) #print 'result', result #img_eli = img_gray.copy() #for best in result[:1]: #yc, xc, a, b = [int(round(x)) for x in best[1:5]] #orientation = best[5] ## Draw the ellipse on the original image #cy, cx = ellipse_perimeter(yc, xc, a, b, orientation) #img_eli[cy, cx] = 1. #g.imshow(img_eli) #g.set_title('detected ellipses') k = axes[2, 2] med_unsharp = median(img_sharp/img_sharp.max(), selem=disk(10)) k.imshow(med_unsharp, cmap='gray') k.set_title('median on unsharp') sharp_med_unsharp = unsharp(med_unsharp) l = axes[2, 3] edges_med = canny(sharp_med_unsharp, sigma=7) #, high_threshold=0.2) #edges_med = gaussian(edges_med, 7) imsave('edges_med.jpg', img_as_int(edges_med)) l.imshow(gaussian(edges_med, 3), cmap='gray') l.set_title('edges from med unsharp') #abcdefghijkl ##i = axes[2,0] ##i.imshow(original_image[:,:,0], cmap='gray') ##i.set_title('red channel') ##j = axes[2,1] ##j.imshow(original_image[:,:,1], cmap='gray') ##j.set_title('green channel') ##k = axes[2,2] ##k.imshow(original_image[:,:,2], cmap='gray') ##k.set_title('blue channel') plt.show()
img_pil_rgba = img_pil_rgb.convert("RGBA") img_rgba = np.asarray(img_pil_rgba) img_rgba.setflags(write=1) return img_rgba path = sys.argv[1] image = io.imread(path) image = image[:, :, :3] image = rank.equalize(image, disk(10)) w, h, d = image.shape pixels = np.reshape(image, (w * h, d)) kmeans = cluster.KMeans(n_clusters=cluster_num) kmeans.fit(pixels) labels = kmeans.labels_.reshape((w, h)) graies = [(rgb2gray(np.average(image[labels == i], axis=0)), i) for i in xrange(cluster_num)] graies.sort()
# # The equalized image [2]_ has a roughly linear cumulative distribution # function for each pixel neighborhood. The local version [3]_ of the # histogram equalization emphasizes every local gray-level variations. # # .. [2] http://en.wikipedia.org/wiki/Histogram_equalization # .. [3] http://en.wikipedia.org/wiki/Adaptive_histogram_equalization from skimage import exposure from skimage.filters import rank noisy_image = img_as_ubyte(data.camera()) # equalize globally and locally glob = exposure.equalize_hist(noisy_image) * 255 loc = rank.equalize(noisy_image, disk(20)) # extract histogram for each image hist = np.histogram(noisy_image, bins=np.arange(0, 256)) glob_hist = np.histogram(glob, bins=np.arange(0, 256)) loc_hist = np.histogram(loc, bins=np.arange(0, 256)) fig, ax = plt.subplots(3, 2, figsize=(10, 10)) ax1, ax2, ax3, ax4, ax5, ax6 = ax.ravel() ax1.imshow(noisy_image, interpolation='nearest', cmap=plt.cm.gray) ax1.axis('off') ax2.plot(hist[1][:-1], hist[0], lw=2) ax2.set_title('Histogram of gray values')
# Display cumulative distribution img_cdf, bins = exposure.cumulative_distribution(img, bins) ax_cdf.plot(bins, img_cdf, 'r') return ax_img, ax_hist, ax_cdf # Load an example image img = img_as_ubyte(data.moon()) # Global equalize img_rescale = exposure.equalize_hist(img) # Equalization selem = disk(30) img_eq = rank.equalize(img, selem=selem) # Display results fig, axes = plt.subplots(2, 3, figsize=(8, 5)) ax_img, ax_hist, ax_cdf = plot_img_and_hist(img, axes[:, 0]) ax_img.set_title('Low contrast image') ax_hist.set_ylabel('Number of pixels') ax_img, ax_hist, ax_cdf = plot_img_and_hist(img_rescale, axes[:, 1]) ax_img.set_title('Global equalise') ax_img, ax_hist, ax_cdf = plot_img_and_hist(img_eq, axes[:, 2]) ax_img.set_title('Local equalize') ax_cdf.set_ylabel('Fraction of total intensity')