def test_bounding_values(): image = img_as_float(data.page()) template = np.zeros((3, 3)) template[1, 1] = 1 result = match_template(img_as_float(data.page()), template) print(result.max()) assert result.max() < 1 + 1e-7 assert result.min() > -1 - 1e-7
def main(): image_rgb = cv2.imread("1-039 (2).jpg") image = cv2.cvtColor(image_rgb, cv2.COLOR_BGR2GRAY) ''' rows = image.shape[0] cols = image.shape[1] print("length: ", len(image)) print("Dimensions: ", image.shape) print("rows,cols: ", rows, cols) ''' text = data.page() print(text.shape) image_show(text) fig, ax = plt.subplots(1, 1) ax.hist(text.ravel(), bins=256, range=[0, 255]) ax.set_xlim(0, 256) ####Basic threshold #segmented = text < 60 #image_show(segmented) ####Thresholding methods #text_threshold = filters.threshold_sauvola(text) #image_show(text < text_threshold) plt.show()
def show_threshold(): fig = plt.figure(figsize=(16, 9)) ax1, ax2 = fig.subplots(1, 2) img = data.page() ax1.axis('off') ax1.imshow(img, cmap='gray') ax1.set_title("raw image") y = im2bw(img, th=128) ax2.axis('off') ax2.imshow(y, cmap='gray') ax2.set_title("binary image") plt.show()
def show_image(image, title): plt.imshow(image, cmap="gray") plt.axis("off") plt.title(title) plt.show() def histogram(image): plt.hist(image, bins=256) plt.show() # show image original camera = data.page() # show_image(camera, "Camera Original") """ show thresholding otsu global """ thresh_global = threshold_otsu(camera) camera_binary_global = camera > thresh_global # show_image(camera_binary_global, "Camera Global") # show histogram with line in thresh otsu # plt.hist(camera.ravel(), bins=256) # plt.axvline(thresh_global, color='r') # plt.title('Histogram camera') # plt.show() """ show difference thresholding otsu local and global
ax[0].set_title('Original') ax[0].axis('off') ax[1].hist(image.ravel(), bins=256) ax[1].set_title('Histogram') ax[1].axvline(thresh, color='r') ax[2].imshow(binary, cmap=plt.cm.gray) ax[2].set_title('Thresholded') ax[2].axis('off') plt.show() ###################################################################### # If you are not familiar with the details of the different algorithms and the # underlying assumptions, it is often difficult to know which algorithm will give # the best results. Therefore, Scikit-image includes a function to evaluate # thresholding algorithms provided by the library. At a glance, you can select # the best algorithm for you data without a deep understanding of their # mechanisms. # from skimage.filters import try_all_threshold img = data.page() # Here, we specify a radius for local thresholding algorithms. # If it is not specified, only global algorithms are called. fig, ax = try_all_threshold(img, figsize=(10, 8), verbose=False) plt.show()
the best algorithm for you data without a deep understanding of their mechanisms. .. [1] https://en.wikipedia.org/wiki/Thresholding_%28image_processing%29 .. seealso:: Presentation on :ref:`sphx_glr_auto_examples_xx_applications_plot_rank_filters.py`. """ import matplotlib import matplotlib.pyplot as plt from skimage import data from skimage.filters import try_all_threshold img = data.page() fig, ax = try_all_threshold(img, figsize=(10, 8), verbose=False) plt.show() ###################################################################### # How to apply a threshold? # ========================= # # Now, we illustrate how to apply one of these thresholding algorithms. # This example uses the mean value of pixel intensities. It is a simple # and naive threshold value, which is sometimes used as a guess value. # from skimage.filters import threshold_mean
# # __A pairing between spatial information (position) and some other kind of information (value).__ # $$ \vec{x} \rightarrow \vec{f} $$ # # We are used to seeing images in a grid format where the position indicates the row and column in the grid and the intensity (absorption, reflection, tip deflection, etc) is shown as a different color. We take an example here of text on a page. # In[9]: from skimage.io import imread import matplotlib.pyplot as plt import numpy as np from skimage.data import page import pandas as pd from skimage.filters import gaussian, median, threshold_triangle page_image = page() just_text = median(page_image, np.ones( (2, 2))) - 255 * gaussian(page_image, 20.0) plt.imshow(page_image, cmap="bone") # In[10]: xx, yy = np.meshgrid(np.arange(page_image.shape[1]), np.arange(page_image.shape[0])) page_table = pd.DataFrame( dict( x=xx.ravel(), y=yy.ravel(), intensity=page_image.ravel(), is_text=just_text.ravel() > 0,
import matplotlib import matplotlib.pyplot as plt from skimage import io from skimage.data import page from skimage.filters import (threshold_otsu, threshold_niblack, threshold_sauvola) from skimage.filters import threshold_mean matplotlib.rcParams['font.size'] = 9 io.use_plugin('matplotlib', 'imread') image = page() image_base = "images/crop/v5/" image_file = "image_3_bin_400x400_crop.jpg" image = io.imread(image_base + image_file) binary_global = image > threshold_otsu(image) #binary_global = image > threshold_mean(image) window_size = 63 thresh_niblack = threshold_niblack(image, window_size=window_size, k=0.8) thresh_sauvola = threshold_sauvola(image, window_size=window_size) binary_niblack = image > thresh_niblack binary_sauvola = image > thresh_sauvola plt.figure(figsize=(8, 7)) plt.subplot(2, 2, 1) plt.imshow(image, cmap=plt.cm.gray) plt.title('Original')
ax[0].axis('off') ax[1].hist(image.ravel(), bins=256) ax[1].set_title('Histogram') ax[1].axvline(thresh, color='r') ax[2].imshow(binary, cmap=plt.cm.gray) ax[2].set_title('Thresholded') ax[2].axis('off') plt.show() ###################################################################### # If you are not familiar with the details of the different algorithms and the # underlying assumptions, it is often difficult to know which algorithm will give # the best results. Therefore, Scikit-image includes a function to evaluate # thresholding algorithms provided by the library. At a glance, you can select # the best algorithm for you data without a deep understanding of their # mechanisms. # from skimage.filters import try_all_threshold img = data.page() # Here, we specify a radius for local thresholding algorithms. # If it is not specified, only global algorithms are called. fig, ax = try_all_threshold(img, radius=20, figsize=(10, 8), verbose=False) plt.show()
import numpy as np import cv2 as cv2 from skimage import data, io import matplotlib.pyplot as plt import matplotlib from sklearn import preprocessing from skimage.transform import resize import random im = data.page() if len(im.shape) == 3: # converting to gray scale if image is RGB im = cv2.cvtColor(im, cv2.COLOR_RGB2GRAY) # h 400 * w 600 fig = plt.figure(figsize=(30, 30)) rows = 2 columns = 2 fig.add_subplot(rows, columns, 1) plt.imshow(im, cmap="gray") out_thresholded = cv2.adaptiveThreshold( src=im, maxValue=255, adaptiveMethod=cv2.ADAPTIVE_THRESH_MEAN_C, thresholdType=cv2.THRESH_BINARY, blockSize=11, C=2, ) fig.add_subplot(rows, columns, 2) plt.imshow(out_thresholded, cmap="gray") plt.show()
the best algorithm for you data without a deep understanding of their mechanisms. .. [1] https://en.wikipedia.org/wiki/Thresholding_%28image_processing%29 .. seealso:: Presentation on :ref:`sphx_glr_auto_examples_xx_applications_plot_rank_filters.py`. """ import matplotlib import matplotlib.pyplot as plt from skimage import data from skimage.filters import try_all_threshold img = data.page() # Here, we specify a radius for local thresholding algorithms. # If it is not specified, only global algorithms are called. fig, ax = try_all_threshold(img, radius=20, figsize=(10, 8), verbose=False) plt.show() ###################################################################### # How to apply a threshold? # ========================= # # Now, we illustrate how to apply one of these thresholding algorithms. # This example uses the mean value of pixel intensities. It is a simple # and naive threshold value, which is sometimes used as a guess value. #
import matplotlib.pyplot as plt from skimage.morphology import diameter_closing from skimage import data from skimage.morphology import closing from skimage.morphology import square datasets = { 'retina': { 'image': data.microaneurysms(), 'figsize': (15, 9), 'diameter': 10, 'vis_factor': 3, 'title': 'Detection of microaneurysm' }, 'page': { 'image': data.page(), 'figsize': (15, 7), 'diameter': 23, 'vis_factor': 1, 'title': 'Text detection' } } for dataset in datasets.values(): # image with printed letters image = dataset['image'] figsize = dataset['figsize'] diameter = dataset['diameter'] fig, ax = plt.subplots(2, 3, figsize=figsize) # Original image
from skimage.segmentation import mark_boundaries import time import matplotlib.image as mpimg exec(open('/Users/Salim_Andre/Desktop/IMA/PRAT/code/pd_segmentation_0.py').read()) exec(open('/Users/Salim_Andre/Desktop/IMA/PRAT/code/tree.py').read()) ### DATASET PATH_img = '/Users/Salim_Andre/Desktop/IMA/PRAT/' # path to my own images swans=mpimg.imread(PATH_img+'swans.jpg'); baby=mpimg.imread(PATH_img+'baby.jpg'); img_set = [data.astronaut(), data.camera(), data.coins(), data.checkerboard(), data.chelsea(), \ data.coffee(), data.clock(), data.hubble_deep_field(), data.horse(), data.immunohistochemistry(), \ data.moon(), data.page(), data.rocket(), swans, baby] ### IMAGE I=img_as_float(img_set[0]); ### PARAMETERS FOR 0-HOMOLOGY GROUPS mode='customized'; n_superpixels=10000; RV_epsilon=30; gauss_sigma=0.5; list_events=[800]; n_pxl_min_ = 30; density_excl=0.0; entropy_thresh_=1.1;
.. [1] http://en.wikipedia.org/wiki/Otsu's_method """ import matplotlib import matplotlib.pyplot as plt from skimage import data from skimage.morphology import disk from skimage.filters import threshold_otsu, rank from skimage.util import img_as_ubyte from skimage import io # Load image file matplotlib.rcParams['font.size'] = 9 img = img_as_ubyte(data.page()) image = io.imread('dataset/ID_0ed10ec08.dcm') radius = 15 selem = disk(radius) local_otsu = rank.otsu(img, selem) threshold_global_otsu = threshold_otsu(img) global_otsu = img >= threshold_global_otsu fig, ax = plt.subplots(2, 2, figsize=(8, 5)) ax1, ax2, ax3, ax4 = ax.ravel() fig.colorbar(ax1.imshow(img, cmap=plt.cm.gray), ax=ax1, orientation='horizontal')
""" import numpy as np import matplotlib.pyplot as plt from skimage.morphology import diameter_closing from skimage import data from skimage.morphology import closing from skimage.morphology import square datasets = { 'retina': {'image': data.microaneurysms(), 'figsize': (15, 9), 'diameter': 10, 'vis_factor': 3, 'title': 'Detection of microaneurysm'}, 'page': {'image': data.page(), 'figsize': (15, 7), 'diameter': 23, 'vis_factor': 1, 'title': 'Text detection'} } for dataset in datasets.values(): # image with printed letters image = dataset['image'] figsize = dataset['figsize'] diameter = dataset['diameter'] fig, ax = plt.subplots(2, 3, figsize=figsize) # Original image ax[0, 0].imshow(image, cmap='gray', aspect='equal',
# -*- coding: utf-8 -*- """ Created on Thu Jun 18 11:22:58 2015 @author: George """ import matplotlib.pyplot as plt from skimage import data from skimage.filters import threshold_otsu, threshold_adaptive image = data.page() global_thresh = threshold_otsu(image) binary_global = image > global_thresh block_size = 40 binary_adaptive = threshold_adaptive(image, block_size, offset=10) fig, axes = plt.subplots(nrows=3, figsize=(7, 8)) ax0, ax1, ax2 = axes plt.gray() ax0.imshow(image) ax0.set_title('Image') ax1.imshow(binary_global) ax1.set_title('Global thresholding')
from PIL import Image import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from pylab import * from skimage import data # Binarisation started = data.page() plt.imshow(started, cmap=cm.gray) plt.show() imageArray = np.zeros(shape(started)).astype('uint8') threshold = 90 imageArray[started < threshold] = 0 imageArray[started >= threshold] = 255 plt.imshow(imageArray, cmap=cm.gray) plt.show()
from PIL import Image import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from pylab import * from skimage import data scanned = data.page() plt.imshow(scanned, cmap=cm.gray) thres = np.zeros(shape(scanned)).astype('uint8') threshold = 90 thres[scanned < threshold] = 0 thres[scanned >= threshold] = 255 plt.imshow(thres, cmap=cm.gray) plt.show()
binarization," Pattern Recognition 33(2), pp. 225-236, 2000. :DOI:`10.1016/S0031-3203(99)00055-2` """ import matplotlib import matplotlib.pyplot as plt from skimage.data import page from skimage.filters import (threshold_otsu, threshold_niblack, threshold_sauvola) matplotlib.rcParams['font.size'] = 9 image = page() binary_global = image > threshold_otsu(image) window_size = 25 thresh_niblack = threshold_niblack(image, window_size=window_size, k=0.8) thresh_sauvola = threshold_sauvola(image, window_size=window_size) binary_niblack = image > thresh_niblack binary_sauvola = image > thresh_sauvola plt.figure(figsize=(8, 7)) plt.subplot(2, 2, 1) plt.imshow(image, cmap=plt.cm.gray) plt.title('Original') plt.axis('off')
import numpy as np import matplotlib.pyplot as plt import skimage.data as data import skimage.segmentation as seg import skimage.filters as filters import skimage.draw as draw import skimage.color as color def image_show(image, nrows=1, ncols=1, cmap='gray'): fig, ax = plt.subplots(nrows=nrows, ncols=ncols, figsize=(14, 14)) ax.imshow(image, cmap='gray') plt.show() ax.axis('off') return fig, ax text = data.page() image_show(text) fig, ax = plt.subplots(1, 1) ax.hist(text.ravel(), bins=32, range=[0, 256]) ax.set_xlim(0, 256) plt.show() image_slic = seg.slic(text, n_segments=2) image_show(color.label2rgb(image_slic, text, kind='avg')) # image = data.binary_blobs() # plt.imshow(image) # plt.show()
.. [1] http://en.wikipedia.org/wiki/Otsu's_method """ import matplotlib import matplotlib.pyplot as plt from skimage import data from skimage.morphology import disk from skimage.filters import threshold_otsu, rank from skimage.util import img_as_ubyte matplotlib.rcParams['font.size'] = 9 img = img_as_ubyte(data.page()) radius = 15 selem = disk(radius) local_otsu = rank.otsu(img, selem) threshold_global_otsu = threshold_otsu(img) global_otsu = img >= threshold_global_otsu fig, ax = plt.subplots(2, 2, figsize=(8, 5)) ax1, ax2, ax3, ax4 = ax.ravel() fig.colorbar(ax1.imshow(img, cmap=plt.cm.gray), ax=ax1, orientation='horizontal') ax1.set_title('Original')
# pixels of the local neighborhood defined by a structuring element. # # The example compares the local threshold with the global threshold # `skimage.filters.threshold_otsu`. # # .. note:: # # Local is much slower than global thresholding. A function for global # Otsu thresholding can be found in : `skimage.filters.threshold_otsu`. # # .. [4] http://en.wikipedia.org/wiki/Otsu's_method from skimage.filters.rank import otsu from skimage.filters import threshold_otsu p8 = data.page() radius = 10 selem = disk(radius) # t_loc_otsu is an image t_loc_otsu = otsu(p8, selem) loc_otsu = p8 >= t_loc_otsu # t_glob_otsu is a scalar t_glob_otsu = threshold_otsu(p8) glob_otsu = p8 >= t_glob_otsu fig, ax = plt.subplots(2, 2, sharex=True, sharey=True) ax1, ax2, ax3, ax4 = ax.ravel()
import numpy as np import matplotlib.pyplot as plt from skimage import data #chargement de l'image et l'affichage de son histogramme image = data.page() plt.hist(image.flatten(), 256) plt.show() plt.imshow(image, plt.cm.gray) plt.axis('off') plt.show() #on défini la fonction qui prend l'image et la fenêtre de pixel et retourne une image binarisée def seuil_sauvola(I, a, k): #les constantes L = a // 2 a2 = a * a R = 128 image = np.copy(I) #Pour éviter les problèmes de bords on ajoute des bordures de largeur L image = np.pad(image, L, mode='edge') #les dimensions de l'image mx, my = image.shape #initialisation des élèments pour le calcul des sommes som1 = [0 for i in range(my)] som2 = 0
def test_page(): """ Test that "page" image can be loaded. """ data.page()
53: 'y', 54: 'z' } def greedy_search(raw, blank=0): max_id = raw.argmax(2).ravel() msk = max_id[1:] != max_id[:-1] max_id = max_id[1:][msk] return max_id[max_id != blank] # net = planer.onnx2planer('./crnn.onnx') net = planer.read_net('./crnn-ocr') x = page()[:40, :150].astype('float32') w = 48 * x.shape[1] // x.shape[0] x = planer.resize(x, (48, w)) x = (x - 0.5) / (90 / 255) x = x[None, None, :, :] net.timer = {} start = time() y = net(x) print(time() - start) for k in net.timer: print(k, net.timer[k]) pred = greedy_search(y)
The example compares the local threshold with the global threshold `skimage.filter.threshold_otsu`. .. note:: Local thresholding is much slower than global one. There exists a function for global Otsu thresholding: `skimage.filter.threshold_otsu`. .. [4] http://en.wikipedia.org/wiki/Otsu's_method """ from skimage.filter.rank import otsu from skimage.filter import threshold_otsu p8 = data.page() radius = 10 selem = disk(radius) # t_loc_otsu is an image t_loc_otsu = otsu(p8, selem) loc_otsu = p8 >= t_loc_otsu # t_glob_otsu is a scalar t_glob_otsu = threshold_otsu(p8) glob_otsu = p8 >= t_glob_otsu plt.figure() plt.subplot(2, 2, 1) plt.imshow(p8, cmap=plt.cm.gray)
def test_binarize(self): b = Binarizer() binary_sauvola = b.binarize([page()], Method.SAUVOLA) plt.imshow(binary_sauvola[0], cmap=plt.cm.gray) plt.show()