This commit is contained in:
Nguyễn Anh Khoa
2019-05-14 22:37:19 +07:00
commit a43837539e
250 changed files with 26352 additions and 0 deletions

View File

@ -0,0 +1,134 @@
import cv2 as cv
import numpy as np
from numpy import fft
import matplotlib.pyplot as plt
from scipy import ndimage
from scipy import signal
from scipy import fftpack
def create_histogram(img):
size = img.shape[0]*img.shape[1]
hist = np.zeros(8, dtype=np.float)
for row in range(img.shape[0]):
for col in range(img.shape[1]):
hist[img[row][col]] += 1
return hist/size
def create_sum_histogram(hist):
sum_hist = np.zeros(8,dtype=np.float)
sum_hist[0] = hist[0]
for x in range(1,8):
sum_hist[x] = sum_hist[x-1] + hist[x]
return sum_hist
def dft(signal):
N = len(signal)
x = np.array(range(N))
x = np.tile(x,(N,1))
u = x.copy().T
M = np.exp((-1j*2*np.pi*x*u)/N)
return np.matmul(M,signal)
def show_dft_vector(N):
x = np.array(range(N))
x = np.tile(x,(N,1))
u = x.copy().T
M = np.exp((-1j*2*np.pi*x*u)/N)
print(M)
def dct(signal):
N = len(signal)
x = np.array(range(N))
x = np.tile(x,(N,1))
u = x.copy().T
M = np.cos((2*x+1)*u*np.pi/(2*N))
a1 = [np.sqrt(1/N)]
a2 = np.repeat(np.array([np.sqrt(2/N)]),N-1)
a = np.concatenate((a1,a2),axis = 0)
return np.matmul(M,signal)*a
def show_dct(N):
x = np.array(range(N))
x = np.tile(x,(N,1))
u = x.copy().T
M = np.cos((2*x+1)*u*np.pi/(2*N))
a1 = [np.sqrt(1/N)]
a2 = np.repeat(np.array([np.sqrt(2/N)]),N-1)
a = np.concatenate((a1,a2),axis = 0)
a = np.repeat(a,4)
a = np.reshape(a,(4,4))
return M*a
def bai1():
I = np.array([[5,0,0,1,2],
[2,1,5,1,2],
[7,1,5,1,2],
[7,4,5,4,3],
[7,1,6,1,3]])
Kx = np.array([[-1,0,1],
[-2,0,2],
[-1,0,1]])
Ky = Kx.T
Gx = ndimage.convolve(I,Kx,mode='reflect')
Gy = ndimage.convolve(I,Ky,mode='reflect')
print('Gradient vector at (0,0): (' + str(Gx[0,0]) + ',' + str(Gy[0,0]) +')')
print('Gradient vector at (1,1): (' + str(Gx[1,1]) + ',' + str(Gy[1,1]) +')')
print('Gradient vector at (0,3): (' + str(Gx[0,3]) + ',' + str(Gy[0,3]) +')')
h = create_histogram(I)
plt.plot(h,color = 'b')
plt.xlim([0,7])
plt.show()
sumhist = create_sum_histogram(h)
new_I = I.copy()
for x in range(I.shape[0]):
for y in range(I.shape[1]):
new_I[x][y] = int(np.round(sumhist[I[x][y]]*7))
new_h = create_histogram(new_I)
new_h_sum = create_sum_histogram(new_h)
plt.plot(sumhist,color = 'r')
plt.plot(new_h_sum,color = 'b')
plt.xlim([0,7])
plt.show()
print(new_I)
def bai2():
# a)
print('Cau 2a)')
show_dft_vector(2)
print(dft([1,3]))
# b)
print('Cau b)')
fx = np.array([1,3])
fu = dft(fx)
print(fu)
print('Chung minh truc giao chuan:')
base_vector = show_dct(4)
for v in base_vector:
print(np.sum(v**2))
for x in range(base_vector.shape[0]):
for y in range(x,base_vector.shape[0]):
if x == y:
continue
print(np.dot(base_vector[x],base_vector[y]))
fx = np.array([1,0,1])
fxx = np.array([1,0,1,0])
print(dct(fxx))
def bai3():
A = np.array([[1/np.sqrt(2),-1/np.sqrt(2),3],
[1/np.sqrt(2),1/np.sqrt(2),-3*2**0.5+3],
[0,0,1]])
P1 = np.array([2,3,1])
pixel = np.round(np.matmul(np.linalg.inv(A),P1))
print(pixel)
bai1()
bai2()
bai3()

View File

@ -0,0 +1,107 @@
from skimage.exposure import rescale_intensity
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
import math
def convolve(image, kernel):
(iH, iW) = image.shape[:2]
(kH, kW) = kernel.shape[:2]
kernel = kernel[::-1]
pad = (kW - 1) // 2
image = cv.copyMakeBorder(image, pad, pad, pad, pad, cv.BORDER_REPLICATE)
output = np.zeros((iH,iW), dtype="float32")
for y in np.arange(pad, iH + pad):
for x in np.arange(pad, iW + pad):
roi = image[y - pad:y+pad+1, x - pad:x + pad + 1]
k =(roi * kernel).sum()
output[y - pad, x - pad] = k
output = rescale_intensity(output, in_range=(0,255))
output = (output * 255).astype("uint8")
return output
I = np.array([ [5,0,0,1,2],
[2,1,5,1,2],
[7,1,5,1,2],
[7,4,5,4,3],
[7,1,6,1,3] ])
sobelX = np.array((
[-1,0,1],
[-2,0,2],
[-1,0,1]), dtype="int")
sobelY = np.array((
[-1,-1,-1],
[-2, 0, 2],
[-1, 0, 1]), dtype="int")
H,W = I.shape
D_x = convolve(I,sobelX)
D_y = convolve(I,sobelY)
result_a = []
for i in range(H):
temp = []
for j in range(W):
temp += [(D_x[i,j],D_y[i,j])]
result_a.append(temp)
print("1A\n",result_a)
def create_histogram(img):
assert len(img.shape) == 2
H,W = img.shape
sum = H * W
histogram = np.zeros(shape=(8,), dtype = float)
for row in range(img.shape[0]):
for col in range(img.shape[1]):
histogram[img[row,col]] += 1 / sum
return histogram
def visualize_histogram(histogram, name):
index = np.arange(len(histogram))
plt.bar(index,histogram)
plt.xlabel('Intensity', fontsize = 5)
plt.ylabel('Frequency', fontsize = 5)
plt.title(name)
plt.show()
def histogram_equation(histogram, img):
c = np.cumsum(histogram)
print(c)
m_table = np.array([]).astype(np.uint8)
m_table = c * 7
for row in range(img.shape[0]):
for col in range(img.shape[1]):
img[row,col] = m_table[img[row,col]]
return img
visualize_histogram(create_histogram(I),"1B")
print("1C\n",histogram_equation(create_histogram(I),I))
def DFT1D(array):
N = array.shape[0]
# (a[x, y], b[x, y]) = (x, y)
a = np.tile(np.arange(0, N), (N, 1))
b = a.copy().T
W = np.exp(-2j*np.pi/N*a*b)
return np.around(np.dot(W, array), 2)
def DCT1D(array):
N = array.shape[0]
factor = math.pi / N
C = np.zeros((N, N), dtype = np.float32)
for x in range(N):
C[0][x] = math.sqrt(1/N) * math.cos((x + 0.5) * 0 * factor)
for u in range(N)[1:]:
for x in range(N):
C[u][x] = math.sqrt(2/N) * math.cos((x + 0.5) * u * factor)
return C, np.matmul(C, array)
print("2A\n",DFT1D(np.array([1,3])))
C, F = DCT1D(np.array([1,0,1,0]))
print("2B\nC=\n", C)
print("F=",F)

84
python_scripts/FTs.py Normal file
View File

@ -0,0 +1,84 @@
import numpy as np
import scipy.ndimage as ndi
import matplotlib.pyplot as plt
def imshow(img, cap=None):
if np.amax(img) > 255:
img = img / (np.amax(img)) * 255
img.astype(np.uint8)
fig = plt.figure(figsize=(4, 4))
if cap is not None:
plt.title(cap)
plt.imshow(img, cmap="gray")
plt.axis("off")
plt.show()
def shift(array):
n = array.shape[0]
t = array[0:int(n / 2), 0:int(n / 2)].copy()
array[0:int(n / 2), 0:int(n / 2)] = array[int(n / 2):n, int(n / 2):n]
array[int(n / 2):n, int(n / 2):n] = t
t = array[0:int(n / 2), int(n / 2):n].copy()
array[0:int(n / 2), int(n / 2):n] = array[int(n / 2):n, 0:int(n / 2)]
array[int(n / 2):n, 0:int(n / 2)] = t
return array
def padding(img):
s = 2**np.ceil(np.log2(np.amax(img.shape))).astype(np.int32)
height = s - img.shape[0]
width = s - img.shape[1]
left = width // 2
right = width - left
top = height // 2
down = height - top
shape_ = [[top, down], [left, right]]
return np.pad(img, shape_, 'constant')
def dft1d(array):
N = array.shape[0]
# (a[x, y], b[x, y]) = (x, y)
a = np.tile(np.arange(0, N), (N, 1))
b = a.copy().T
W = np.exp(-2j * np.pi / N * a * b)
return np.around(np.dot(W, array), 2)
def idft1d(array):
N = array.shape[0]
# (a[x, y], b[x, y]) = (x, y)
a = np.tile(np.arange(0, N), (N, 1))
b = a.copy().T
W = np.exp(2j * np.pi / N * a * b) / N
return np.around(np.dot(W, array), 2)
def fft1d(array):
m = array.shape[0]
if m == 1:
return array
elif m % 2 == 0:
even = fft1d(array[::2])
odd = fft1d(array[1::2])
Wm = np.exp(-2j * np.pi / m * np.arange(int(m / 2)))
half1 = even + odd * Wm
half2 = even - odd * Wm
return np.concatenate([half1, half2])
else:
raise ValueError("Wrong dimension")
def fft(array):
n = array.shape[0]
if np.log2(n) % 1 != 0:
return dft1d(array)
else:
return np.around(fft1d(array), 2)
def fft2d(matrix):
temp = np.array([fft(x) for x in matrix]).T
return np.around(np.array([fft(x) for x in temp]).T, 2)

114
python_scripts/Filters.py Normal file
View File

@ -0,0 +1,114 @@
import cv2
import numpy as np
import scipy.ndimage as ndi
import matplotlib.pyplot as plt
# customized imshow function
def imshow(img, cap=None):
if np.amax(img) > 255:
img = img / (np.amax(img)) * 255
img.astype(np.uint8)
fig = plt.figure(figsize=(4, 4))
if cap is not None:
plt.title(cap)
plt.imshow(img, cmap="gray")
plt.axis("off")
plt.show()
def apply(img, ker):
return np.abs(np.fft.ifft2(np.fft.fftshift(np.fft.fft2(img)) * ker).real)
################################################################
# Ideal LowPass Filter kernel
def ilpf(m, n, r):
a = np.tile(np.arange(-n / 2, n / 2), (m, 1))
b = np.tile(np.arange(-m / 2, m / 2), (n, 1)).T
return (a * a + b * b < r * r).astype(np.uint8)
# Print ILPF Result
def apply_ilpf(img, r):
row, col = img.shape
imshow(img(*ilpf(row, col, r)), 'Ideal LowPass Filter\nwith r = ' + str(r))
img = cv2.imread("C:/Users/NGPD/Desktop/2.jpg", cv2.IMREAD_GRAYSCALE)
imshow(img, 'Loaded Image')
apply_ilpf(img, 5)
apply_ilpf(img, 15)
apply_ilpf(img, 30)
apply_ilpf(img, 80)
################################################################
# Butterworth LPF kernel
def blpf(m, n, N, r):
a = np.tile(np.arange(-n / 2, n / 2), (m, 1))
b = np.tile(np.arange(-m / 2, m / 2), (n, 1)).T
return (1 / (1 + ((a * a + b * b) / (r * r))**N))
# Print BLPF Result
def apply_blpf(img, N, r):
row, col = img.shape
imshow(img(*blpf(row, col, N, r)),
'Butterworth LowPass Filter\nwith r = ' + str(r) + ' and n = ' + str(N))
img = cv2.imread("C:/Users/NGPD/Desktop/2.jpg", cv2.IMREAD_GRAYSCALE)
imshow(img, 'Loaded Image')
n = 2
apply_blpf(img, n, 5)
apply_blpf(img, n, 15)
apply_blpf(img, n, 30)
apply_blpf(img, n, 80)
################################################################
# Gaussian LPF kernel
def glpf(m, n, r):
a = np.tile(np.arange(-n / 2, n / 2), (m, 1))
b = np.tile(np.arange(-m / 2, m / 2), (n, 1)).T
return np.exp(-(a * a + b * b) / (2 * r * r))
# Print GLPF Result
def apply_glpf(img, r):
row, col = img.shape
imshow(img(*glpf(row, col, r)), 'Gaussian LowPass Filter\nwith r = ' + str(r))
img = cv2.imread("C:/Users/NGPD/Desktop/2.jpg", cv2.IMREAD_GRAYSCALE)
imshow(img, 'Loaded Image')
apply_glpf(img, 5)
apply_glpf(img, 15)
apply_glpf(img, 30)
apply_glpf(img, 80)
################################################################
img = cv2.imread("C:/Users/NGPD/Desktop/2.jpg", cv2.IMREAD_GRAYSCALE)
m, n = img.shape
a = np.tile(np.arange(-n / 2, n / 2), (m, 1))
b = np.tile(np.arange(-m / 2, m / 2), (n, 1)).T
lap = img(*-(a * a + b * b))
if np.amax(lap) > 255:
lap = lap / (np.amax(lap)) * 255
imshow(img, 'Loaded Image')
imshow(lap, 'Laplacian Filter')
imshow(img - lap, 'g(x, y)')

View File

@ -0,0 +1,46 @@
import cv2
import numpy as np
import scipy.ndimage as ndi
import matplotlib.pyplot as plt
# customized imshow function
def imshow(img, cap=None):
if np.amax(img) > 255:
img = img / (np.amax(img)) * 255
img.astype(np.uint8)
fig = plt.figure(figsize=(4, 4))
if cap is not None:
plt.title(cap)
plt.imshow(img, cmap="gray")
plt.axis("off")
plt.show()
def ilpf(m, n, r):
a = np.tile(np.arange(-n / 2, n / 2), (m, 1))
b = np.tile(np.arange(-m / 2, m / 2), (n, 1)).T
return (a * a + b * b < r * r).astype(np.uint8)
def apply(img, ker):
return np.abs(np.fft.ifft2(np.fft.fftshift(np.fft.fft2(img)) * ker).real)
# generate chess board with size NxN
N = 64
a = np.tile(np.array(1), (int(N / 4), int(N / 4)))
b = np.tile(np.array(0), (int(N / 4), int(N / 4)))
img1 = np.concatenate([a, b], axis=0)
img2 = np.concatenate([b, a], axis=0)
img = np.concatenate([img1, img2], axis=1)
img = np.tile(img, (4, 4))
r, c = img.shape
ker = ilpf(r, c, 30)
res = img(*ker)
imshow(img, 'Created Image')
imshow(ker, 'ILPF Kernel')
imshow(res, 'ILPF Result')

90
python_scripts/hough.py Normal file
View File

@ -0,0 +1,90 @@
import numpy as np
import imageio
import math
def rgb2gray(rgb):
return np.dot(rgb[..., :3], [0.299, 0.587, 0.114]).astype(np.uint8)
def hough_line(img, angle_step=1, lines_are_white=True, value_threshold=5):
"""
Hough transform for lines
Input:
img - 2D binary image with nonzeros representing edges
angle_step - Spacing between angles to use every n-th angle
between -90 and 90 degrees. Default step is 1.
lines_are_white - boolean indicating whether lines to be detected are white
value_threshold - Pixel values above or below the value_threshold are edges
Returns:
accumulator - 2D array of the hough transform accumulator
theta - array of angles used in computation, in radians.
rhos - array of rho values. Max size is 2 times the diagonal
distance of the input image.
"""
# Rho and Theta ranges
thetas = np.deg2rad(np.arange(-90.0, 90.0, angle_step))
width, height = img.shape
diag_len = int(round(math.sqrt(width * width + height * height)))
rhos = np.linspace(-diag_len, diag_len, diag_len * 2)
# Cache some resuable values
cos_t = np.cos(thetas)
sin_t = np.sin(thetas)
num_thetas = len(thetas)
# Hough accumulator array of theta vs rho
accumulator = np.zeros((2 * diag_len, num_thetas), dtype=np.uint8)
# (row, col) indexes to edges
are_edges = img > value_threshold if lines_are_white else img < value_threshold
y_idxs, x_idxs = np.nonzero(are_edges)
# Vote in the hough accumulator
for i in range(len(x_idxs)):
x = x_idxs[i]
y = y_idxs[i]
for t_idx in range(num_thetas):
# Calculate rho. diag_len is added for a positive index
rho = diag_len + int(round(x * cos_t[t_idx] + y * sin_t[t_idx]))
accumulator[rho, t_idx] += 1
return accumulator, thetas, rhos
def show_hough_line(img, accumulator, thetas, rhos, save_path=None):
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 2, figsize=(10, 10))
ax[0].imshow(img, cmap=plt.cm.gray)
ax[0].set_title('Input image')
ax[0].axis('image')
ax[1].imshow(
accumulator, cmap='jet',
extent=[np.rad2deg(thetas[-1]), np.rad2deg(thetas[0]), rhos[-1], rhos[0]])
ax[1].set_aspect('equal', adjustable='box')
ax[1].set_title('Hough transform')
ax[1].set_xlabel('Angles (degrees)')
ax[1].set_ylabel('Distance (pixels)')
ax[1].axis('image')
# plt.axis('off')
if save_path is not None:
plt.savefig(save_path, bbox_inches='tight')
plt.show()
if __name__ == '__main__':
imgpath = '../images/bangdiem.png'
img = imageio.imread(imgpath)
if img.ndim == 3:
img = rgb2gray(img)
accumulator, thetas, rhos = hough_line(img)
idx = np.argmax(accumulator)
rho = rhos[idx / accumulator.shape[1]]
theta = thetas[idx % accumulator.shape[1]]
print ("rho={0:.2f}, theta={1:.0f}".format(rho, np.rad2deg(theta)))
# show_hough_line(img, accumulator, save_path='imgs/output.png')