def preproc(img): selem = disk(60) try: img = autolevel(img, selem) img = exposure.adjust_gamma(img, 2) img = cv2.bilateralFilter(img, 9, 75, 75) except: print(img.shape) pass return (img)
def preproc(img): selem = disk(60) try: img = autolevel(img, selem) img = exposure.adjust_gamma(img, 2) img = cv2.bilateralFilter(img, 9, 75, 75) except Exception as e: traceback.print_tb(e.__traceback__) pass return (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 test_compare_autolevels_16bit(): # compare autolevel(16-bit) and percentile autolevel(16-bit) with p0=0.0 # and p1=1.0 should returns the same arrays image = data.camera().astype(np.uint16) * 4 selem = disk(20) loc_autolevel = rank.autolevel(image, selem=selem) loc_perc_autolevel = rank.autolevel_percentile(image, selem=selem, p0=0.0, p1=1.0) assert_equal(loc_autolevel, loc_perc_autolevel)
def test_compare_autolevels(): # compare autolevel and percentile autolevel with p0=0.0 and p1=1.0 # should returns the same arrays image = util.img_as_ubyte(data.camera()) selem = disk(20) loc_autolevel = rank.autolevel(image, selem=selem) loc_perc_autolevel = rank.autolevel_percentile(image, selem=selem, p0=0.0, p1=1.0) assert_equal(loc_autolevel, loc_perc_autolevel)
def test_compare_autolevels(self): # compare autolevel and percentile autolevel with p0=0.0 and p1=1.0 # should returns the same arrays image = util.img_as_ubyte(data.camera()) selem = disk(20) loc_autolevel = rank.autolevel(image, selem=selem) loc_perc_autolevel = rank.autolevel_percentile(image, selem=selem, p0=.0, p1=1.) assert_equal(loc_autolevel, loc_perc_autolevel)
def test_compare_autolevels_16bit(self): # compare autolevel(16-bit) and percentile autolevel(16-bit) with p0=0.0 # and p1=1.0 should returns the same arrays image = data.camera().astype(np.uint16) * 4 selem = disk(20) loc_autolevel = rank.autolevel(image, selem=selem) loc_perc_autolevel = rank.autolevel_percentile(image, selem=selem, p0=.0, p1=1.) assert_equal(loc_autolevel, loc_perc_autolevel)
def gen_all_filters(art): """ Generate all the filtered versions of the input image, for use in other functions Args: art (numpy.ndarray): The original RGB image, (width, height, 3) Returns: im_smooth (numpy.ndarray): Smoothed grayscale image (width, height) smooth_grad_mag (numpy.ndarray): Gradient magnitude of smoothed, grayscale image (width, height) loc_autolevel (numpy.ndarray): Rank-filtered grayscale image (width, height) sharp_grad_mag (numpy.ndarray): Gradient magnitude of rank-filtered, grayscale image (width, height) """ #Convert to grayscale for edge estimation hsv_art = mpl.colors.rgb_to_hsv(art).astype(np.float32) #The smooth image im_smooth = np.zeros(hsv_art[:, :, 0].shape) ndimage.filters.gaussian_filter(hsv_art[:, :, 2], (10, 10), (0, 0), im_smooth) #Smooth grad image, with thresholding im_x = np.zeros(im_smooth.shape) sigma = 2 ndimage.filters.gaussian_filter(im_smooth, (sigma, sigma), (0, 1), im_x) im_y = np.zeros(im_smooth.shape) ndimage.filters.gaussian_filter(im_smooth, (sigma, sigma), (1, 0), im_y) smooth_grad_mag = np.sqrt(im_y**2 + im_x**2) #Sharp im selem = disk(20) loc_autolevel = autolevel(hsv_art[:, :, 2] / 256.0, selem=selem) #Sharp im grad im_x = np.zeros(loc_autolevel.shape) sigma = 2 ndimage.filters.gaussian_filter(loc_autolevel, (sigma, sigma), (0, 1), im_x) im_y = np.zeros(loc_autolevel.shape) ndimage.filters.gaussian_filter(loc_autolevel, (sigma, sigma), (1, 0), im_y) sharp_grad_mag = np.sqrt(im_y**2 + im_x**2) return im_smooth, smooth_grad_mag, loc_autolevel, sharp_grad_mag
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))
plt.figure('morphology',figsize=(8,8)) plt.subplot(121) plt.title('origin image') plt.imshow(img,plt.cm.gray) plt.axis('off') plt.subplot(122) plt.title('morphological image:black-tophat') plt.imshow(dst,plt.cm.gray) plt.axis('off') plt.show() # ============================================================================= print('''十二、高级滤波''') # ============================================================================= img =color.rgb2gray(data.astronaut()) '''1、autolevel''' auto =rank.autolevel(img, disk(5)) #半径为5的圆形滤波器 plt.figure('filters1',figsize=(8,8)) plt.subplot(121) plt.title('origin image') plt.imshow(img,plt.cm.gray) plt.subplot(122) plt.title('filted image:autolevel') plt.imshow(auto,plt.cm.gray) plt.show() '''2、bottomhat 与 tophat''' auto =rank.bottomhat(img, disk(5)) #半径为5的圆形滤波器 plt.figure('filters2',figsize=(8,8)) plt.subplot(121) plt.title('origin image') plt.imshow(img,plt.cm.gray) plt.subplot(122)
ax6.plot(loc_hist[1][:-1], loc_hist[0], lw=2) ax6.set_title('Histogram of gray values') ###################################################################### # Another way to maximize the number of gray-levels used for an image is to # apply a local auto-leveling, i.e. the gray-value of a pixel is # proportionally remapped between local minimum and local maximum. # # The following example shows how local auto-level enhances the camara man # picture. from skimage.filters.rank import autolevel noisy_image = img_as_ubyte(data.camera()) auto = autolevel(noisy_image.astype(np.uint16), disk(20)) fig, (ax1, ax2) = plt.subplots(1, 2, figsize=[10, 7], sharex=True, sharey=True) ax1.imshow(noisy_image, cmap=plt.cm.gray) ax1.set_title('Original') ax1.axis('off') ax1.set_adjustable('box-forced') ax2.imshow(auto, cmap=plt.cm.gray) ax2.set_title('Local autolevel') ax2.axis('off') ax2.set_adjustable('box-forced') ###################################################################### # This filter is very sensitive to local outliers, see the little white spot
def autolevel(image, disk_size): return rank.autolevel(image, disk(disk_size))
def autolevel(image, nbins): return threshold_isodata(image) return rank.autolevel(image, nbins)
ax[2].imshow(glob, interpolation='nearest', cmap=plt.cm.gray) ax[2].axis('off') ax[3].plot(glob_hist[1][:-1], glob_hist[0], lw=2) ax[3].set_title('Histogram of gray values') ax[4].imshow(loc, interpolation='nearest', cmap=plt.cm.gray) ax[4].axis('off') ax[5].plot(loc_hist[1][:-1], loc_hist[0], lw=2) ax[5].set_title('Histogram of gray values') plt.tight_layout() # Local-based contrast enhancement from skimage.filters.rank import autolevel noisy_image = img_as_ubyte(data.camera()) auto = autolevel(noisy_image.astype(np.uint16), disk(20)) fig, ax = plt.subplots(ncols=2, figsize=(10, 5), sharex=True, sharey=True) ax[0].imshow(noisy_image, cmap=plt.cm.gray) ax[0].set_title('Original') ax[1].imshow(auto, cmap=plt.cm.gray) ax[1].set_title('Local autolevel') for a in ax: a.axis('off') plt.tight_layout() # Morphological Contrast Enhancements from skimage.filters.rank import enhance_contrast noisy_image = img_as_ubyte(data.camera())
这个词在photoshop里面翻译成自动色阶, 用局部直方图来对图片进行滤波分级。 该滤波器局部地拉伸灰度像素值的直方图,以覆盖整个像素值范围。 ''' # 图像局部增强2 plt.figure(num=3, figsize=(12, 8), dpi=96) #设置窗口大小 plt.suptitle('zi dong se jie') imgS = Image.open('./car.jpg').convert('RGB').convert('L') # 图像数据类型的转换 imgUByte = img_as_float(imgS) img = color.rgb2gray(np.array(imgUByte)) auto = sfr.autolevel(img, disk(5)) #半径为5的圆形滤波器 plt.subplot(221) plt.title('jun heng zhi fang tu') plt.hist(im4.flatten(), 256) plt.subplot(222) plt.title('jun heng img') plt.imshow(im4, plt.cm.gray) plt.subplot(223) plt.title('origin image') plt.imshow(img, plt.cm.gray) plt.subplot(224) plt.title('zi dong se jie image')
plt.tight_layout() ###################################################################### # Another way to maximize the number of gray-levels used for an image is to # apply a local auto-leveling, i.e. the gray-value of a pixel is # proportionally remapped between local minimum and local maximum. # # The following example shows how local auto-level enhances the camara man # picture. from skimage.filters.rank import autolevel noisy_image = img_as_ubyte(data.camera()) auto = autolevel(noisy_image.astype(np.uint16), disk(20)) fig, ax = plt.subplots(ncols=2, figsize=(10, 5), sharex=True, sharey=True) ax[0].imshow(noisy_image, cmap=plt.cm.gray) ax[0].set_title('Original') ax[1].imshow(auto, cmap=plt.cm.gray) ax[1].set_title('Local autolevel') for a in ax: a.axis('off') plt.tight_layout() ######################################################################
from skimage import data, color import matplotlib.pyplot as plt from skimage.morphology import disk import skimage.filters.rank as sfr original_image = color.rgb2gray(data.camera()) plt.imshow(original_image, cmap=plt.cm.gray) filtered_images = [] filtered_images.append(sfr.autolevel(original_image, disk(5))) filtered_images.append(sfr.bottomhat(original_image, disk(5))) filtered_images.append(sfr.tophat(original_image, disk(5))) filtered_images.append(sfr.enhance_contrast(original_image, disk(5))) filtered_images.append(sfr.entropy(original_image, disk(5))) filtered_images.append(sfr.equalize(original_image, disk(5))) filtered_images.append(sfr.gradient(original_image, disk(5))) filtered_images.append(sfr.maximum(original_image, disk(5))) filtered_images.append(sfr.minimum(original_image, disk(5))) filtered_images.append(sfr.mean(original_image, disk(5))) filtered_images.append(sfr.median(original_image, disk(5))) filtered_images.append(sfr.modal(original_image, disk(5))) filtered_images.append(sfr.otsu(original_image, disk(5))) filtered_images.append(sfr.threshold(original_image, disk(5))) filtered_images.append(sfr.subtract_mean(original_image, disk(5))) filtered_images.append(sfr.sum(original_image, disk(5))) name_list = [ 'autolevel', 'bottomhat', 'tophat', 'enhance_contrast', 'entropy', 'equalize', 'gradient', 'maximum', 'minimum', 'mean', 'median', 'modal', 'otsu', 'threshold', 'subtract_mean', 'sum' ]
def binarize(source, Threshtype, gamma, md_filter, g_blur, autolvl, fg_color, \ laplacian, scharr, sobel, lowpass, asize, bsize, wsize, thresh): global img global img_bin img = source img = adjust_gamma(img, gamma) # applies a low-pass filter if (lowpass == 1): img = Hamming_window(img, wsize) # making a 5x5 array of all 1's for median filter, and a disk for the autolevel filter darray = np.zeros((5, 5)) + 1 selem = disk(bsize) # applying median filter if (md_filter == 1): img = median(img, darray) # applying gaussian blur if (g_blur == 1): img = cv2.GaussianBlur(img, (bsize, bsize), 0) # applying autolevel filter if (autolvl == 1): img = autolevel(img, selem=selem) # applying a scharr filter, and then taking that image and weighting it 25% with the original # this should bring out the edges without separating each "edge" into two separate parallel ones if (scharr == 1): ddepth = cv2.CV_16S grad_x = cv2.Scharr(img, ddepth, 1, 0) grad_y = cv2.Scharr(img, ddepth, 0, 1) abs_grad_x = cv2.convertScaleAbs(grad_x) abs_grad_y = cv2.convertScaleAbs(grad_y) dst = cv2.addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0) dst = cv2.convertScaleAbs(dst) img = cv2.addWeighted(img, 0.75, dst, 0.25, 0) img = cv2.convertScaleAbs(img) # applying sobel filter if (sobel == 1): scale = 1 delta = 0 ddepth = cv2.CV_16S grad_x = cv2.Sobel(img, ddepth, 1, 0, ksize=3, scale=scale, delta=delta, borderType=cv2.BORDER_DEFAULT) grad_y = cv2.Sobel(img, ddepth, 0, 1, ksize=3, scale=scale, delta=delta, borderType=cv2.BORDER_DEFAULT) abs_grad_x = cv2.convertScaleAbs(grad_x) abs_grad_y = cv2.convertScaleAbs(grad_y) dst = cv2.addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0) dst = cv2.convertScaleAbs(dst) img = cv2.addWeighted(img, 0.75, dst, 0.25, 0) img = cv2.convertScaleAbs(img) # applying laplacian filter if (laplacian == 1): ddepth = cv2.CV_16S dst = cv2.Laplacian(img, ddepth, ksize=5) # dst = cv2.Canny(img, 100, 200); # canny edge detection test dst = cv2.convertScaleAbs(dst) img = cv2.addWeighted(img, 0.75, dst, 0.25, 0) img = cv2.convertScaleAbs(img) # this is my attempt at a fast fourier transformation with a band pass filter # I would highly reccomend taking a look at this and seeing if its working right # I had no idea what I was doing but I think it works, it could use some more testing because it just # kinda makes the image blurry, but that could be the band pass filter #if fourier == 1: #rows, cols = img.shape #m = cv2.getOptimalDFTSize(rows) #n = cv2.getOptimalDFTSize(cols) #padded = cv2.copyMakeBorder(img, 0, m - rows, 0, n - cols, cv2.BORDER_CONSTANT, value=[0, 0, 0]) #planes = [np.float32(padded), np.zeros(padded.shape, np.float32)] #complexI = cv2.merge(planes) #dft = cv2.dft(np.float32(complexI), flags=cv2.DFT_COMPLEX_OUTPUT) #dft_shift = np.fft.fftshift(dft) # Band pass filter mask #rows, cols = img.shape #crow, ccol = int(rows / 2), int(cols / 2) #mask = np.zeros((rows, cols, 2), np.uint8) #r_out = 80 #r_in = 10 #center = [crow, ccol] #x, y = np.ogrid[:rows, :cols] #mask_area = np.logical_and(((x - center[0]) ** 2 + (y - center[1]) ** 2 >= r_in ** 2), #((x - center[0]) ** 2 + (y - center[1]) ** 2 <= r_out ** 2)) #mask[mask_area] = 1 # apply mask and inverse DFT #fshift = dft_shift * mask #f_ishift = np.fft.ifftshift(fshift) #img_back = cv2.idft(f_ishift) #img_back = cv2.magnitude(img_back[:, :, 0], img_back[:, :, 1]) #cv2.normalize(img_back, img_back, 0, 255, cv2.NORM_MINMAX) #img = cv2.convertScaleAbs(img_back) img_bin, ret = thresh_it(img, Threshtype, fg_color, asize, thresh) return img, img_bin, ret