def edges(im): original = skimage.io.imread(im) grayscale = rgb2gray(original) edge_sobel = filters.sobel(grayscale) edge_scharr = filters.scharr(grayscale) edge_prewitt = filters.prewitt(grayscale) diff_scharr_prewitt = compare_images(edge_scharr, edge_prewitt) diff_scharr_sobel = compare_images(edge_scharr, edge_sobel) max_diff = np.max(np.maximum(diff_scharr_prewitt, diff_scharr_sobel)) fig, axes = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True, figsize=(8, 8)) axes = axes.ravel() # axes[0].imshow(im, cmap=plt.cm.gray) # axes[0].set_title('Original image') axes[1].imshow(edge_scharr, cmap=plt.cm.gray) axes[1].set_title('Scharr Edge Detection') axes[2].imshow(diff_scharr_prewitt, cmap=plt.cm.gray, vmax=max_diff) axes[2].set_title('Scharr - Prewitt') axes[3].imshow(diff_scharr_sobel, cmap=plt.cm.gray, vmax=max_diff) axes[3].set_title('Scharr - Sobel') for ax in axes: ax.axis('off') plt.tight_layout() plt.show()
def compare(file): sImg = gray2rgb(imread(source + '/' + file)) aImg = imread(answer + '/' + file) diff = compare_images(sImg, aImg, method='diff') if np.sum(diff) < 1e-7: print('Result is correct') else: print('See diff file for difference') imsave('diff.png', diff)
def histogram_match(src, ref): # Open reference and source files reference = io.imread(ref) image = io.imread(src) image_gray = color.rgb2gray(image) # Histogram matching matched = exposure.match_histograms(image, reference, multichannel=True) matched_gray = color.rgb2gray(matched) # Calculate the diff between image and matched diff = util.compare_images(matched_gray, image_gray, method='diff') diff = color.gray2rgb(diff) return (image, reference, matched, diff)
def image_filtering_anisotropic(): """ Anisotropic image filtering methods """ # reading, corrupting image with noise, and removing nan, negative values. image_ref = io.imread('input.jpg', as_gray=True) image_retina = speckle_generator(image_ref) image_retina = np.nan_to_num(image_retina) image_retina[image_retina < 0] = 1 print("Input Image SNR: " + str(signal_to_noise(image_retina))) fig, axs = plt.subplots(3, 1, figsize=(4, 9.5)) axs[0].imshow(image_retina, cmap='gray', vmin=0, vmax=255) axs[0].set_title("Input") log_input = log_transformation(image_retina) median_output = exp_transformation(median_filtering(log_input)) compute_diff = compare_images(image_retina, median_output, method='checkerboard', n_tiles=(4, 4)) io.imsave("diff_input_output.jpg", compute_diff) print("Median SNR: " + str(signal_to_noise(median_output))) axs[1].imshow(median_output, cmap='gray') axs[1].set_title("Median Filtering") bil_output = exp_transformation(bilateral_filtering(log_input)) print("Bilateral SNR: " + str(signal_to_noise(bil_output))) axs[2].imshow(bil_output, cmap='gray') axs[2].set_title("Bilateral Filtering") for j in range(3): axs[j].set_xticks([]) axs[j].set_yticks([]) plt.tight_layout() plt.show()
# .. [2] B. Jaehne, H. Scharr, and S. Koerkel. Principles of filter design. # In Handbook of Computer Vision and Applications. Academic Press, # 1999. # # .. [3] https://en.wikipedia.org/wiki/Prewitt_operator x, y = np.ogrid[:100, :100] # Creating a rotation-invariant image with different spatial frequencies. image_rot = np.exp(1j * np.hypot(x, y)**1.3 / 20.).real edge_sobel = filters.sobel(image_rot) edge_scharr = filters.scharr(image_rot) edge_prewitt = filters.prewitt(image_rot) diff_scharr_prewitt = compare_images(edge_scharr, edge_prewitt) diff_scharr_sobel = compare_images(edge_scharr, edge_sobel) max_diff = np.max(np.maximum(diff_scharr_prewitt, diff_scharr_sobel)) fig, axes = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True, figsize=(8, 8)) axes = axes.ravel() axes[0].imshow(image_rot, cmap=plt.cm.gray) axes[0].set_title('Original image') axes[1].imshow(edge_scharr, cmap=plt.cm.gray) axes[1].set_title('Scharr Edge Detection')
def _plot_view_checkerboard(self, num_clip, step_clip, in_ori_data, in_warped_data, gs, plot_column, view_flag): for clip_idx in range(num_clip): clip_off_set = (clip_idx - 2) * step_clip ori_slice = self._clip_image(in_ori_data, view_flag, offset=clip_off_set) warped_slice = self._clip_image(in_warped_data, view_flag, offset=clip_off_set) ref_slice = self._clip_image(self._ref_img.get_data(), view_flag, offset=clip_off_set) jet_cm = plt.get_cmap('jet') gray_cm = plt.get_cmap('gray') slice_ori_rescale = exposure.rescale_intensity( ori_slice, in_range=(self._vmin, self._vmax), out_range=(0, 1)) # slice_ori_rgb = color.gray2rgba(slice_ori_rescale) slice_ori_rgb = jet_cm(slice_ori_rescale) slice_warped_rescale = exposure.rescale_intensity( warped_slice, in_range=(self._vmin, self._vmax), out_range=(0, 1)) # slice_warped_rgb = color.gray2rgb(slice_warped_rescale) slice_warped_rgb = jet_cm(slice_warped_rescale) slice_ref_rescale = exposure.rescale_intensity( ref_slice, in_range=(self._vmin, self._vmax), out_range=(0, 1)) # slice_ref_rgb = color.gray2rgb(slice_ref_rescale) slice_ref_rgb = gray_cm(slice_ref_rescale) ori_ref_checkerboard = np.zeros(slice_ref_rgb.shape) warped_ref_checkerboard = np.zeros(slice_ref_rgb.shape) for dim in range(slice_ref_rgb.shape[2]): ori_ref_checkerboard[:, :, dim] = \ compare_images(slice_ori_rgb[:, :, dim], slice_ref_rgb[:, :, dim], method='checkerboard', n_tiles=self._checkerboard_n_tiles) warped_ref_checkerboard[:, :, dim] = \ compare_images(slice_warped_rgb[:, :, dim], slice_ref_rgb[:, :, dim], method='checkerboard', n_tiles=self._checkerboard_n_tiles) plt.axis('off') # Ori + ref ax0 = plt.subplot(gs[clip_idx, 2 * plot_column]) plt.axis('off') plt.imshow(ori_ref_checkerboard) ax0.set_title(f'{view_flag}, ori + ref ({clip_off_set})', fontsize=self._sub_title_font_size) # warped + ref ax1 = plt.subplot(gs[clip_idx, 2 * plot_column + 1]) plt.axis('off') plt.imshow(warped_ref_checkerboard) ax1.set_title(f'{view_flag}, warped + ref ({clip_off_set})', fontsize=self._sub_title_font_size)
such as exposure manipulations, filtering, and restauration. This example shows how to easily compare two images with various approaches. """ import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec from skimage import data, transform, exposure from skimage.util import compare_images img1 = data.coins() img1_equalized = exposure.equalize_hist(img1) img2 = transform.rotate(img1, 5) comp_equalized = compare_images(img1, img1_equalized, method='checkerboard') diff_rotated = compare_images(img1, img2, method='diff') blend_rotated = compare_images(img1, img2, method='blend') ###################################################################### # Checkerboard # ============ # # The `checkerboard` method alternates tiles from the first and the second # images. fig = plt.figure(figsize=(8, 9)) gs = GridSpec(3, 2) ax0 = fig.add_subplot(gs[0, 0]) ax1 = fig.add_subplot(gs[0, 1])
def check_pdf_data( self, data, contents=-1, pages=-1, intern_check:bool=False ): ''' Prüft pdf data mit vorher gespeicherten data Erzeugt in unittest dir auf dem Server ein dir 'check', um dort die Vergleichsdaten zu speichern Parameters ---------- data : dict - content: dict page_names : dict - overlays: dict - pages: int - pdf_filename: string - pdf_filepath: string - png_filename: string - png_filepath: string contents : int Anzahl der Seiten im Content pages : int Anzahl der Seiten im PDF intern_check: Wenn True wird in tests und nicht im normalem pdf Ablegeort geprüft. Default is False Returns ------- None. ''' self.assertIn("pdf_filepath", data, "PDF data fehlerhaft filename fehlt" ) self.assertIn("png_filepath", data, "PNG data fehlerhaft filepath fehlt" ) check = {} # # Vorbereitungen # if intern_check == True: test_dir = osp.join( ABSPATH, "resources" ) else: test_dir = os.path.dirname( data["pdf_filepath"] ) check_dir = osp.join( test_dir, "check" ) # create the folders if not already exists if not os.path.exists( check_dir ): try: os.makedirs( check_dir ) except IOError as e: print("Unable to create dir.", e) # Dateiname für den Inhalt festlegen json_test_name = osp.join( test_dir, data["pdf_filename"] ) + ".json" json_check_name = osp.join( check_dir, data["pdf_filename"] ) + ".json" pdf_check_name = osp.join( check_dir, data["pdf_filename"] ) png_check_name = osp.join( check_dir, data["png_filename"] ) png_new_name = data["png_filepath"] # immer den content in unittest ablegen with open(json_test_name, "w" ) as json_file: json.dump( data["content"] , json_file, indent=2 ) # beim erstenmal content nach check kopieren if not os.path.exists( json_check_name ): try: copyfile(json_test_name, json_check_name) except IOError as e: print("Unable to copy file.", e) # beim erstenmal pdf nach check kopieren if not os.path.exists( pdf_check_name ): try: copyfile(data["pdf_filepath"], pdf_check_name) except IOError as e: print("Unable to copy file.", e) # beim erstenmal png nach check kopieren if not os.path.exists( png_check_name ): try: copyfile(png_new_name, png_check_name) except IOError as e: print("Unable to copy file.", e) # # Überprüfungen # # passende check daten (json_check_name) laden with open( json_check_name ) as json_file: check = json.load( json_file ) page_names = data["content"].keys() # Anzahl der Bereiche prüfen if contents > -1: self.assertEqual( len( page_names ), contents, "Anzahl der content Bereiche in '{}' stimmt nicht.".format( data["pdf_filepath"] ) ) # Namen der Bereiche self.assertEqual( page_names, check.keys(), "Namen der Bereiche '{}' stimmt nicht.".format( data["pdf_filepath"] ) ) # Anzahl der Seiten prüfen if pages > -1: self.assertEqual( data["pages"], pages, "Anzahl der Seiten in '{}' stimmt nicht.".format( data["pdf_filepath"] ) ) # einige content Inhalte prüfen from bs4 import BeautifulSoup for page_name, content in data["content"].items(): bs_data = BeautifulSoup( content, 'html.parser') bs_check = BeautifulSoup( check[ page_name ], 'html.parser') # die text Bereiche data_text_list = bs_data.find_all('div', {"class": "text"} ) check_text_list = bs_check.find_all('div', {"class": "text"} ) self.assertEqual( data_text_list, check_text_list, "PDF content .text in '{}' ist fehlerhaft".format( data["pdf_filepath"] ) ) # erzeugte png vergleichen und diff speichern png_check = img_io.imread( png_check_name ) png_new = img_io.imread( png_new_name ) self.assertEqual( png_check.shape, png_new.shape, "Die Bildgrößen in '{}' stimmen nicht.".format( data["pdf_filepath"] ) ) # Bild verleich erstellen und speichern compare = compare_images(png_check, png_new, method='diff') img_io.imsave( png_new_name + ".diff.png", compare ) # gesamt check der Bilder def check_mse(imageA, imageB): # the 'Mean Squared Error' between the two images is the # sum of the squared difference between the two images; # NOTE: the two images must have the same dimension err = np.sum((imageA.astype("float") - imageB.astype("float")) ** 2) err /= float(imageA.shape[0] * imageA.shape[1]) # return the MSE, the lower the error, the more "similar" # the two images are return err # MeanCheck durchführen try: mse = check_mse( png_check, png_new ) except: mse = -1 self.assertEqual( 0.0, mse, "Der PNG Vergleichsbild MSE stimmt nicht. Diff image '{}' prüfen".format( data["png_filepath"] + ".diff.png" ) )
# pip install scikit-image import skimage.io as io from skimage.util import compare_images import numpy as np im0 = io.imread('a0.jpg') # median of source images im1 = io.imread('a1.jpg') # source image 1 im2 = io.imread('a2.jpg') # source image 2 im3 = io.imread('a3.jpg') # source image 3 im_all = np.copy(im0) th = 0.1 # d = np.max(np.abs(im2 - im0), -1) d = compare_images(im1, im0, method='diff') d = np.max(np.abs(d), -1) im_all[d > th] = im1[d > th] io.imsave("d1.jpg", d > th) d = compare_images(im2, im0, method='diff') d = np.max(np.abs(d), -1) im_all[d > th] = im2[d > th] io.imsave("d2.jpg", d > th) d = compare_images(im3, im0, method='diff') d = np.max(np.abs(d), -1) im_all[d > th] = im3[d > th] io.imsave("d3.jpg", d > th) io.imsave("im_all.jpg", im_all)
image = imread('../skripsi-april/luka_hitam/1.jpg', as_gray=False) height, width, channel = image.shape image_xyz = np.empty((height, width, channel)) image_lab1 = np.empty( (height, width, channel)) #Citra LAB dengan rumus dari buku mask = imread('../skripsi-april/luka_hitam/1_region.png', as_gray=True) #image_xyz = rgb2xyz(image) #image_lab2 = rgb2lab(image, illuminant='D65', observer='2') #Citra LAB langsung dari skimage #result = Image.blend(mask, image_lab1, alpha=0.5) mask_resize = resize(mask, (height, width, 3)) hasil1 = compare_images(mask_resize, image, method='blend') #hasil overlay mask dengan LAB Manual #hasil2 = compare_images(mask_resize, image_lab2, method='blend') #hasil overlay mask dengan LAB skimage for i in range(height): for j in range(width): for k in range(channel): R = hasil1.item(i, j, 0) G = hasil1.item(i, j, 1) B = hasil1.item(i, j, 2) # Rumus RGB ke XYZ dari buku X = (R * 0.49000 + G * 0.31000 + B * 0.20000) / 0.17697 Y = (R * 0.17697 + G * 0.81240 + B * 0.01063) / 0.17697 Z = (R * 0.00000 + G * 0.01000 + B * 0.99000) / 0.17697 # normalisasi nilai XYZ supaya berada dalam rentang 0 sampai 1