Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save LeslieWongCV/c7e30f2f633aced96c0a37fe8ce08a17 to your computer and use it in GitHub Desktop.
Save LeslieWongCV/c7e30f2f633aced96c0a37fe8ce08a17 to your computer and use it in GitHub Desktop.
Image Processing Bundle
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
import numpy as np
from collections import Counter
list = np.array([[2,2,2,2,3,3],[0,0,0,2,2,0],[0,0,0,1,3,2],[0,0,4,2,1,0],[4,2,1,4,2,0],[1,0,3,1,0,0]])
#list = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]])
#list = np.array(range(20)).reshape(4,5) 生成顺序矩阵
#list = np.random.randint(0,4,(6,6))
print('Oringial List:','\n',list)
matrix = np.array(list)
#a=np.argmax(np.bincount(matrix.flat))
#np.bincount返回list里0-9的出现次数
#np.argmax 返回最大数的索引 两函数联合使用找到list里出现最多次数的数字
list_1=[]
list_2=[]
for i in range(0,list.shape[0]):#黑白格分开
for j in range(0,list.shape[1]):
if(((i%2==0)&(j%2==0))+((i%2!=0)&(j%2!=0))):
list_1.append(matrix[i][j])
else:
list_2.append(matrix[i][j])
print('list1:',list_1)
print('list2:',list_2)
list1_max = np.argmax(np.bincount(list_1))
list2_max = np.argmax(np.bincount(list_2))
print('What factor list1 has most:',list1_max)
print('What factor list2 has most:',list2_max)
list1_index = np.bincount(list_1)
list2_index = np.bincount(list_2)
print('list1 index:',list1_index)
print('list2 index:',list2_index)
if (list1_max==list2_max): #如果相等
list1_index[np.argmax(list1_index)] = np.min(list1_index)#[0,0,5,4,1,2] --> [0,0,0,4,1,2] 最大的变最小,第二变最大
list2_index[np.argmax(list2_index)] = np.min(list2_index)
if(np.max(list1_index)>>np.max(list2_index)): #第二大的数出现的次数(出现第二多的数的次数
list1_max = np.argmax(list1_index)
else:
list2_max = np.argmax(list2_index)
print('New max factor for list1:',list1_max)
print('New max fatcor for list2:',list2_max)
print('Updated index for list1:',list1_index)
print('Updated index for list2:',list2_index)
list_coret = np.zeros((list.shape[0],list.shape[1]),npq.int)
for i in range(0,list.shape[0]):
for j in range(0,list.shape[1]):
if (((i % 2 == 0) & (j % 2 == 0)) + ((i % 2 != 0) & (j % 2 != 0))):
list_coret[i][j] = list1_max
else:
list_coret[i][j] = list2_max
step = list.shape[0]*list.shape[1] - np.max(list1_index) - np.max(list2_index)
print('Corrected matrix:','\n',list_coret)
print("It takes %s step(s) to convert"%step)
# coding: utf-8
# In[20]:
#环境
import scipy
from scipy import misc
import imageio
from scipy import ndimage
import numpy as np
import matplotlib.pyplot as plt
#导入图像
lion = imageio.imread('/Users/leslie/Desktop/革命成果-学术/LENA.jpg')
#plt.imshow(lion, cmap = plt.get_cmap('gray'))
#plt.show()
# In[23]:
#变成灰度图
lion_gray = np.dot(lion[...,:3], [0.299, 0.587, 0.114])
#lion_gray = lion_gray.astype('int32')
#plt.imshow(lion_gray, cmap = plt.get_cmap('gray'))
#plt.show()
# In[30]:
#高斯模糊,降噪
lion_gray_blurred = ndimage.gaussian_filter(lion_gray, sigma=1.0) # sigma值根据图像变化
#plt.imshow(lion_gray_blurred, cmap = plt.get_cmap('gray'))
#plt.show()
# In[31]:
# 同sobel算子
#sobel算子也可以是其他矩阵,这里选择最大梯度是2的矩阵
def SobelFilter(img, direction):
if(direction == 'x'):
Gx = np.array([[-1,0,+1], [-2,0,+2], [-1,0,+1]])
Res = ndimage.convolve(img, Gx)
if(direction == 'y'):
Gy = np.array([[-1,-2,-1], [0,0,0], [+1,+2,+1]])
Res = ndimage.convolve(img, Gy)
return Res
# In[32]:
# 正则化像素,正则化后像素<=1
def Normalize(img):
# img = np.multiply(img, 255 / np.max(img))
img = img/np.max(img)
return img
# In[33]:
#X轴应用Sobel算子
gx = SobelFilter(lion_gray_blurred, 'x')
gx = Normalize(gx)
#plt.imshow(gx, cmap = plt.get_cmap('gray'))
#plt.show()
# In[34]:
#Y轴应用Sobel算子
gy = SobelFilter(lion_gray_blurred, 'y')
gy = Normalize(gy)
#plt.imshow(gy, cmap = plt.get_cmap('gray'))
#plt.show()
# In[35]:
# 应用SCIPY自带的函数实现Sobel算子,进行验证
#dx = ndimage.sobel(lion_gray_blurred, axis=1, mode='constant', cval=0.0) # horizontal derivative
#dy = ndimage.sobel(lion_gray_blurred, axis=0, mode='constant', cval=0.0) # vertical derivative
dx = ndimage.sobel(lion_gray_blurred, axis=1) # horizontal derivative
dy = ndimage.sobel(lion_gray_blurred, axis=0) # vertical derivative
# In[36]:
# In[37]:
#计算获得的梯度的大小 NB使得每个像素都<=1
Mag = np.hypot(gx,gy)
Mag = Normalize(Mag)
# In[39]:
# 计算梯度方向
Gradient = np.degrees(np.arctan2(gy,gx))
# In[40]:
# In[42]:
#得到边界
def NonMaxSupWithInterpol(Gmag, Grad, Gx, Gy):
NMS = np.zeros(Gmag.shape)
for i in range(1, int(Gmag.shape[0]) - 1):
for j in range(1, int(Gmag.shape[1]) - 1):
if((Grad[i,j] >= 0 and Grad[i,j] <= 45) or (Grad[i,j] < -135 and Grad[i,j] >= -180)):
yBot = np.array([Gmag[i,j+1], Gmag[i+1,j+1]])
yTop = np.array([Gmag[i,j-1], Gmag[i-1,j-1]])
x_est = np.absolute(Gy[i,j]/Gmag[i,j])
if (Gmag[i,j] >= ((yBot[1]-yBot[0])*x_est+yBot[0]) and Gmag[i,j] >= ((yTop[1]-yTop[0])*x_est+yTop[0])):
NMS[i,j] = Gmag[i,j]
else:
NMS[i,j] = 0
if((Grad[i,j] > 45 and Grad[i,j] <= 90) or (Grad[i,j] < -90 and Grad[i,j] >= -135)):
yBot = np.array([Gmag[i+1,j] ,Gmag[i+1,j+1]])
yTop = np.array([Gmag[i-1,j] ,Gmag[i-1,j-1]])
x_est = np.absolute(Gx[i,j]/Gmag[i,j])
if (Gmag[i,j] >= ((yBot[1]-yBot[0])*x_est+yBot[0]) and Gmag[i,j] >= ((yTop[1]-yTop[0])*x_est+yTop[0])):
NMS[i,j] = Gmag[i,j]
else:
NMS[i,j] = 0
if((Grad[i,j] > 90 and Grad[i,j] <= 135) or (Grad[i,j] < -45 and Grad[i,j] >= -90)):
yBot = np.array([Gmag[i+1,j] ,Gmag[i+1,j-1]])
yTop = np.array([Gmag[i-1,j] ,Gmag[i-1,j+1]])
x_est = np.absolute(Gx[i,j]/Gmag[i,j])
if (Gmag[i,j] >= ((yBot[1]-yBot[0])*x_est+yBot[0]) and Gmag[i,j] >= ((yTop[1]-yTop[0])*x_est+yTop[0])):
NMS[i,j] = Gmag[i,j]
else:
NMS[i,j] = 0
if((Grad[i,j] > 135 and Grad[i,j] <= 180) or (Grad[i,j] < 0 and Grad[i,j] >= -45)):
yBot = np.array([Gmag[i,j-1] ,Gmag[i+1,j-1]])
yTop = np.array([Gmag[i,j+1] ,Gmag[i-1,j+1]])
x_est = np.absolute(Gy[i,j]/Gmag[i,j])
if (Gmag[i,j] >= ((yBot[1]-yBot[0])*x_est+yBot[0]) and Gmag[i,j] >= ((yTop[1]-yTop[0])*x_est+yTop[0])):
NMS[i,j] = Gmag[i,j]
else:
NMS[i,j] = 0
return NMS
# 获取非最大抑制输出
NMS = NonMaxSupWithInterpol(Mag, Gradient, gx, gy)
NMS = Normalize(NMS)
# In[45]:
#双阈值
#连接图像1和2
def DoThreshHyst(img):
highThresholdRatio = 0.2
lowThresholdRatio = 0.15
GSup = np.copy(img)
h = int(GSup.shape[0])
w = int(GSup.shape[1])
highThreshold = np.max(GSup) * highThresholdRatio
lowThreshold = highThreshold * lowThresholdRatio
x = 0.1
oldx=0
#使用while循环使循环继续执行,直到强边的数量不变,即连接到强边的所有弱边都被找到。
while(oldx != x):
oldx = x
for i in range(1,h-1):
for j in range(1,w-1):
if(GSup[i,j] > highThreshold):
GSup[i,j] = 1
elif(GSup[i,j] < lowThreshold):
GSup[i,j] = 0
else:
if((GSup[i-1,j-1] > highThreshold) or
(GSup[i-1,j] > highThreshold) or
(GSup[i-1,j+1] > highThreshold) or
(GSup[i,j-1] > highThreshold) or
(GSup[i,j+1] > highThreshold) or
(GSup[i+1,j-1] > highThreshold) or
(GSup[i+1,j] > highThreshold) or
(GSup[i+1,j+1] > highThreshold)):
GSup[i,j] = 1
x = np.sum(GSup == 1)
GSup = (GSup == 1) * GSup # 把在更不严格(图1)阈值图中的,并且没有连接到严格(图2)阈值的图中的边删除,即只保留连接到强边的弱边。
return GSup
# In[ ]:
#Canny 边缘检测的输出
Final_Image = DoThreshHyst(NMS)
plt.imshow(Final_Image, cmap = plt.get_cmap('gray'))
plt.show()
# test = np.arctan2(gx,gy)
# plt.imshow(test, cmap= plt.get_cmap('gray'))
# plt.show()
import numpy as np
import cv2
import scipy
from scipy import signal
import math
sigma1 = sigma2 = 1
sum = 0
gaussian = np.zeros([5, 5])
for i in range(5):
for j in range(5):
gaussian[i, j] = math.exp(-1 / 2 * (np.square(i - 3) / np.square(sigma1) # 生成二维高斯分布矩阵
+ (np.square(j - 3) / np.square(sigma2)))) / (2 * math.pi * sigma1 * sigma2)
sum = sum + gaussian[i, j]
Gaussian_op = gaussian / sum
LENA = cv2.imread('/Users/leslie/Desktop/革命成果-学术/LENA_FULL.jpg', 0)
LENA_f = np.copy(LENA)
LENA_f_ = LENA_f.astype('float')
#####################################Step1 高斯模糊#####################################
#Gaussian_op = 1/139*np.array([[2,4,5,4,2],[4,9,12,9,4],[5,12,15,12,5],[4,9,12,9,4],[2,4,5,4,2]]) #5*5 高斯内核
blur = scipy.signal.convolve(LENA_f_,Gaussian_op,'same')
#####################################Step2 计算梯度幅值和方向#####################################
G_x = np.array([[-1,0,1],[-2,0,2],[-1,0,1]]) #Sobel Operator
G_y = np.array([[-1,-2,-1],[0,0,0],[1,2,1]])
X = scipy.signal.convolve2d(blur,G_x,'same')
Y = scipy.signal.convolve2d(blur,G_y,'same')
# X = np.convolve(G_x,LENA_f_,'same') numpy.convolve 只支持1D卷积
# Y = np.convolve(G_y,LENA_f_,'same')
X_abs = abs(X)
Y_abs = abs(Y)
G = X_abs + Y_abs
sharp = G + LENA_f_
sharp = np.where(sharp<0,0,np.where(sharp>255,255,sharp))
sharp = sharp.astype('uint8')
# Gaussian_op = 1/139*np.array([[12,4,5,4,2],[4,9,12,9,4],[5,12,15,12,5],[4,9,12,9,4],[2,4,5,4,2]]) #5*5 高斯内核
# blur = scipy.signal.convolve(LENA_f_,Gaussian_op,'same')
# #####################################Step2 计算梯度幅值和方向#####################################
# G_x = np.array([[-1,0,1],[-2,0,2],[-1,0,1]]) #Sobel Operator
# G_y = np.array([[-1,-2,-1],[0,0,0],[1,2,1]])
#
# X = scipy.signal.convolve2d(blur,G_x,'same')
# Y = scipy.signal.convolve2d(blur,G_y,'same')
#
# # X = np.convolve(G_x,LENA_f_,'same') numpy.convolve 只支持1D卷积
# # Y = np.convolve(G_y,LENA_f_,'same')
# X_abs = abs(X)
# Y_abs = abs(Y)
# G = X_abs + Y_abs
#
# sharp1 = G + LENA_f_
# sharp1 = np.where(sharp<0,0,np.where(sharp>255,255,sharp))
# sharp1 = sharp.astype('uint8')
cv2.imshow('Sharp',sharp)
#cv2.imshow('Sharp1',sharp1)
cv2.waitKey()
#blur_ = blur.astype('uint8') #unsigned int 用于显示
#cv2.imshow('blur',blur_)
#cv2.waitKey()
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View raw

(Sorry about that, but we can’t show files that are this big right now.)

Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View raw

(Sorry about that, but we can’t show files that are this big right now.)

Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment