def readImage(path_image, convert): if (convert): im = Image.open(path_image).convert('L') else: im = Image.open(path_image) im = scipy.misc.fromimage(im) return im
import numpy, math import scipy.misc import matplotlib.pyplot as plt import matplotlib.patches as mpatches from skimage.morphology import label from scipy.misc.pilutil import Image from skimage.measure import regionprops from skimage.filters.thresholding import threshold_otsu # opening the image and converting it to grayscale a = Image.open('C:/Users/Maria/Desktop/1.png').convert('L') # a is converted to an ndarray a = scipy.misc.fromimage(a) # threshold value is determined by # using Otsu's method thresh = threshold_otsu(a) # the pixels with intensity greater than # theshold are kept b = a > thresh # labelling is performed on b c = label(b) # c is converted from an ndarray to an image c1 = scipy.misc.toimage(c) # c1 is saved as label_output.png c1.save('../Figures/label_output.png') # on the labelled image c, regionprops is performed d = regionprops(c, properties=['Area','Centroid','BoundingBox']) # the following command creates an empty plot of # dimension 6 inch by 6 inch fig, ax = plt.subplots(ncols=1,nrows=1,figsize=(6, 6))
import scipy.misc as scm from scipy.misc.pilutil import Image orig_image = Image.open('./test.jpg') image1 = scm.fromimage(orig_image) inv_image = 255 - image1 inverted_image = scm.toimage(inv_image) inverted_image.save('./test01.jpg')
for i in range(first_bin, last_bin) : # calculate background entropy ent_back = 0 term = 0.5 / P1[i] for j in range(1, i) : ent_back -= hist[j] * np.log(1 - term*P1[j-1]) ent_back *= term # calculate foreground entropy ent_fore = 0 term = 0.5 / P2[i] for j in range(i+1, 256) : ent_fore -= hist[j] * np.log(1 - term*P2[j-1]) ent_fore *= term # set threshold to value where difference in entropy is minimal tot_ent = abs(ent_back - ent_fore) if (tot_ent < min_ent) : min_ent = tot_ent threshold = i return threshold # test case from scipy.misc.pilutil import Image a = Image.open('Rat_Hippocampal_Neuron.png').convert('L') adata = scipy.misc.fromimage(a) outimg = scipy.misc.toimage(adata > shanbhag(adata)) outimg.show()
# mi.imsave('test.jpg', test) digit_arr = digit_arr / 255.0 digit_arr = digit_arr.reshape(-1, 28, 28, 1) # predict results results = cnnModel.predict(digit_arr) # select the indix with the maximum probability accuracy = np.amax(results, axis=1) results = np.argmax(results, axis=1) ketqua = [results[0], accuracy[0]] # results = pd.Series(result,name="Label") return ketqua model = reStoreModel() direction = 'input/pic.png' input_img = Image.open(direction).convert('L') # ============================================================================= # img = input_img.crop((585, 675, 653, 701)) # getDigit1(img) # getDigit2(img) # digit1_location = 'input/digit1.jpg' # digit2_location = 'input/digit2.jpg' # digit1 = recognizeDigit(model, digit1_location) # digit2 = recognizeDigit(model, digit2_location) # if digit2[0] != 0: # digit2[0] = 5 # print("Ket qua: %s,%s (%s)" %(digit1[0], digit2[0], digit1[1])) # ============================================================================= coordinates = []
def read_image(self, path): print('call read_image') return Image.open(path).convert('L')
import scipy.misc from skimage import filter from scipy.misc.pilutil import Image # opening the image and converting it to grayscale a = Image.open('../Figures/cir.png').convert('L') # performing Sobel filter b = filter.sobel(a) # b is converted from an ndarray to an image b = scipy.misc.toimage(b) b.save('../Figures/sobel_cir.png')
import numpy, math import scipy.misc import scipy.fftpack as fftim from scipy.misc.pilutil import Image # opening the image and converting it to grayscale a = Image.open('../Figures/endothelium.png').\ convert('L') # a is converted to an ndarray b = scipy.misc.fromimage(a) # performing FFT c = fftim.fft2(b) # shifting the Fourier frequency image d = fftim.fftshift(c) # intializing variables for convolution function M = d.shape[0] N = d.shape[1] # H is defined and # values in H are initialized to 1 H = numpy.ones((M, N)) center1 = M / 2 center2 = N / 2 d_0 = 30.0 # cut-off radius t1 = 1 # the order of BHPF t2 = 2 * t1 # defining the convolution function for BHPF for i in range(1, M): for j in range(1, N): r1 = (i - center1)**2 + (j - center2)**2
import cmath from joblib import Parallel, delayed # In[ ]: #DFT implementation With 4 nested loops (very slow) as decribed in book #used multi processing to run for loops in parallel (Not very good in speeding up ) def calc(m, n, kk, ll): s = complex(0) s = img_float32[m, n] * exp(-2j * np.pi * ((kk * m / M) + (ll * n / N))) return s if __name__ == '__main__': image = Image.open("png.png").convert('L') img_float32 = np.asarray(image, dtype=float) M = np.size(image, 0) #generate height and N = np.size(image, 1) #width to loop over them out = np.zeros((M, N), dtype=complex) for k in range(0, M): for l in range(0, N): s = complex(0) s += Parallel(n_jobs=120)(delayed(calc)(m=x, n=y, kk=k, ll=l) for x in range(0, M) for y in range(0, N)) out[k, l] = s dft_shift = np.fft.fftshift(out) magnitude_spectrum = 20 * np.log(np.abs(dft_shift))
import matplotlib.pyplot as plt import matplotlib.cm as cm import scipy.misc as mi import pandas as pd import numpy as np from scipy.misc.pilutil import Image #directory navigation i.e. path to image path1 = '/home/austen/PycharmProjects/Polar Nephelometer/Data/05-25-2017/Sum25Images_Covered.BMP' path2 = '/home/austen/PycharmProjects/Polar Nephelometer/Data/05-25-2017/Sum25Images_LightLeakage.BMP' #Image.open reads the BMP as an image format im1 = Image.open(path1) im2 = Image.open(path2) #imread reads the image as a Matrix, the other a 2D array imArray1 = mi.fromimage(im1) imArray2 = mi.fromimage(im2) imArrayDiff = imArray2 - imArray1 f, ax = plt.subplots(1,2) ax[0].imshow(imArray2, cmap=cm.Greys_r) ax[0].set_title('Holes Uncovered') ax[1].imshow(imArray1, cmap=cm.Greys_r) ax[1].set_title('Holes Covered') plt.show()
import numpy as np import scipy.ndimage from scipy.misc.pilutil import Image # opening the image and converting it to grayscale a = Image.open('../Figures/ultrasound_muscle.png').convert('L') # initializing the filter of size 5 by 5 # the filter is divided by 25 for normalization k = np.ones((5, 5)) / 25 # performing convolution b = scipy.ndimage.filters.convolve(a, k) # b is converted from an ndarray to an image b = scipy.misc.toimage(b) #b.save('../Figures/mean_output.png') b.show()
import scipy.misc import scipy.ndimage from scipy.misc.pilutil import Image # opening the image and converting it to grayscale a = Image.open('../figure/spinwheel.png').convert('L') # performing Laplacian of Gaussian with sigma = 0.9 im1 = scipy.ndimage.filters.gaussian_laplace(a, 0.9, mode='reflect') # performing Laplacian of Gaussian with sigma = 1.3 im2 = scipy.ndimage.filters.gaussian_laplace(a, 1.3, mode='reflect') # determining the difference for obtaining edge b = im1 - im2 # b is converted from an ndarray to an image b = scipy.misc.toimage(b) #b.save('diff_log.png') b.show()
def min_filter(image, size): im = Image.open(image).convert('L') im_new = filters.minimum_filter(im, size=size, mode='reflect') im_new = misc.toimage(im_new) im_new.save('minfilter.png')
## Adaptive Thresholding from scipy.misc.pilutil import Image import scipy.misc import matplotlib.pyplot as plt from skimage.filters import threshold_adaptive # opening the image and converting it to grayscale a = Image.open('text_sample.png').convert('L') # a is converted to an ndarray a1 = scipy.misc.fromimage(a) # adaptive thresholding block_size = 85 temp = threshold_adaptive(a1 ,block_size ,offset = 10) # plot fig = plt.figure() image1 = plt.subplot(121) image2 = plt.subplot(122) # put the images into the window _ = image1.imshow(a) _ = image2.imshow(temp) # hide axis and show window with images image1.axis("on") image2.axis("on") plt.show()
import math, numpy import scipy.misc from scipy.misc.pilutil import Image # opening the image and converting it to grayscale im = Image.open('../Figures/hequalization_input.png').convert('L') # im is converted to an ndarray im1 = scipy.misc.fromimage(im) # finding the maximum and minimum pixel values b = im1.max() a = im1.min() print a, b # converting im1 to float c = im1.astype(float) # contrast stretching transformation im2 = 255 * (c - a) / (b - a) # im2 is converted from an ndarray to an image im3 = scipy.misc.toimage(im2) # saving im3 as contrast_output.png in # Figures folder #im3.save('../Figures/contrast_output2.png') im3.show()
# Mean Filtering import numpy as np import scipy.ndimage from scipy.misc.pilutil import Image import matplotlib.pyplot as mpl # opening the image and converting it to grayscale a = Image.open('lenna.png').convert('L') # initializing the filter of size 5 by 5 # the filter is divided by 25 for normalization k = np.ones((5, 5)) / 25 # performing convolution b = scipy.ndimage.filters.convolve(a, k) # b is converted from an ndarray to an image b = scipy.misc.toimage(b) #b.save('meanfilter_lenna.png') mpl.imshow(b)
# # Load all image in the directory # Don't run yet, it might take a while to load... # In[101]: path = "/Users/edenmolina/Downloads/pics/" # for filename in os.listdir(path): # image = np.array(Image.open('%s/%s'%(path, filename)).convert('L')) # # Load just one image # In[81]: image = np.array( Image.open('/Users/edenmolina/Downloads/pics/6153.jpg').convert('L')) # # View the image # In[82]: plt.figure(figsize=(10, 10)) plt.imshow(image, cmap='gray') plt.show() # # Apply gamma-correction # This is a form of a power law transform where the pixel values in an image at position $\left( i, j \right)$ will be # # $$ # t(i, j) = k I(i, j)^{\gamma} # $$
import numpy, math import scipy.misc import matplotlib.pyplot as plt import matplotlib.patches as mpatches from skimage.measure import label from scipy.misc.pilutil import Image from skimage.measure import regionprops from skimage.filters.thresholding import threshold_otsu # opening the image and converting it to grayscale a = Image.open('../Figures/objects.png').convert('L') # a is converted to an ndarray a = scipy.misc.fromimage(a) # threshold value is determined by # using Otsu's method thresh = threshold_otsu(a) # the pixels with intensity greater than # theshold are kept b = a > thresh # labelling is performed on b c = label(b) # c is converted from an ndarray to an image c1 = scipy.misc.toimage(c) # c1 is saved as label_output.png c1.save('../Figures/label_output.png') # on the labelled image c, regionprops is performed d = regionprops(c) # the following command creates an empty plot of
import numpy as np import scipy.ndimage from scipy.misc.pilutil import Image import matplotlib.pylab as plt # opening the image and converting it to grayscale a = Image.open('ultrasound_muscle.png').convert('L') k = np.fft.fft2(a) plt.imshow(k) plt.show()
import scipy.misc as mi import numpy as np from scipy.misc.pilutil import Image import scipy.ndimage as nd from skimage import filters from skimage import feature import matplotlib.pyplot as plt from skimage.morphology import watershed #from skimage.filter.thresholding import threshold_otsu a = Image.open('resize.jpg').convert('L') a = mi.fromimage(a) thresh = filters.threshold_otsu(a) im_otsu = a > thresh im_otsu = mi.toimage(im_otsu) im_otsu.save('otsu_semoutput.png') im_canny = feature.canny(a, sigma=3) fill_holes = nd.binary_fill_holes(im_canny) fill_holes = mi.toimage(fill_holes) im_canny = mi.toimage(im_canny) im_canny.save('test_canny.jpg') #to remove bushes try to adopt canny edges for leaves, fill holes and then negate obtained mask fill_holes.save('fill_holes.jpg') im_laplace = nd.gaussian_laplace(a, 3) im_laplace = mi.toimage(im_laplace) im_laplace.save('test_laplace.jpg')
import math, numpy import scipy.fftpack as fftim from scipy.misc.pilutil import Image # opening the image and converting it to grayscale a = Image.open('../Figures/fft1.png').convert('L') # a is converted to an ndarray b = numpy.asarray(a) # performing FFT c = abs(fftim.fft2(b)) # shifting the Fourier frequency image d = fftim.fftshift(c) # converting the d to floating type and saving it # as fft1_output.raw in Figures folder d.astype('float').\ tofile('../Figures/fft1_output.raw')
# gray = col.convert('L') # bw = gray.point(lambda x: 0 if x<128 else 255, '1') # bw.save("result_bw.png") import scipy.misc, numpy from skimage import filters from scipy.misc.pilutil import Image from pylab import* import matplotlib.pyplot as plt import matplotlib.patches as mpatches from skimage.morphology import label from scipy.misc.pilutil import Image from skimage.measure import regionprops from skimage.filters import threshold_otsu # opening the image and converting it to grayscale a = Image.open('./images/obama.png').convert('L') # a is converted to an ndarray a = scipy.misc.fromimage(a) # threshold value is determined by # using Otsu's method thresh = threshold_otsu(a) # the pixels with intensity greater than # theshold are kept b = a > thresh # labelling is performed on b c = label(b) # c is converted from an ndarray to an image c1 = scipy.misc.toimage(c) # c1 is saved as label_output.png imshow(c1) show()
## Segmentation from skimage.filters.thresholding import threshold_otsu from scipy.misc.pilutil import Image import scipy.misc import matplotlib.pyplot as plt # opening the image and converting it to grayscale a = Image.open('spinwheel.png').convert('L') # a is converted to an ndarray a1 = scipy.misc.fromimage(a) # performing Otsu's thresholdingSegmentation 143 thresh = threshold_otsu(a1) temp = a1 # pixels with intensity greater than theshold are kept for i in range(0, len(temp)): for j in range(0, len(temp[i])): if temp[i, j] < thresh: temp[i, j] = 0 # b is converted from ndimage to b = scipy.misc.toimage(temp) # plot fig = plt.figure() image1 = plt.subplot(121) image2 = plt.subplot(122) # put the images into the window _ = image1.imshow(a)
import scipy.misc import scipy.ndimage from scipy.misc.pilutil import Image # opening the image and converting it to grayscale a = Image.open('../Figures/ct_saltandpepper.png').convert('L') # performing the median filter b = scipy.ndimage.filters.median_filter(a, size=5, footprint=None, output=None, mode='reflect', cval=0.0, origin=0) # b is converted from an ndarray to an image b = scipy.misc.toimage(b) #b.save('../Figures/median_output.png') b.show()
import scipy.misc import scipy.ndimage from scipy.misc.pilutil import Image # opening the image and converting it to grayscale a = Image.open('../Figures/vhuman_t1.png').convert('L') # performing Laplacian of Gaussian b = scipy.ndimage.filters.gaussian_laplace(a, 1, mode='reflect') # b is converted from an ndarray to an image b = scipy.misc.toimage(b) b.save('../Figures/log_vh1.png')
import scipy.misc import scipy.ndimage from scipy.misc.pilutil import Image # opening the image and converting it to grayscale a = Image.open('../Figures/wave.png').convert('L') # performing maximum filter b = scipy.ndimage.filters.maximum_filter(a, size=5) # b is converted from an ndarray to an image b = scipy.misc.toimage(b) b.save('../Figures/maxo.png')
import numpy as np import scipy.ndimage from scipy.misc.pilutil import Image # Median filter is one of the most popular non-linear filters. # A sliding window is chosen and is placed on the image at the pixel position (i, j). # Median is a value that divides the list into two equal halves. img = Image.open("../dog1.jpeg").convert('L') # performing the median filter b = scipy.ndimage.filters.median_filter(img, size=5, footprint=None, output=None, mode='reflect', cval=0.0, origin=0) b = scipy.misc.toimage(b) b.save("../dog2.jpeg")