commit 512eee503be72ca24c021d9f1bec74d057186757
Author: ydk <1595898818@qq.com>
Date: Sun Jul 31 19:29:03 2022 +0800
first commit
diff --git a/.idea/.gitignore b/.idea/.gitignore
new file mode 100644
index 0000000..26d3352
--- /dev/null
+++ b/.idea/.gitignore
@@ -0,0 +1,3 @@
+# Default ignored files
+/shelf/
+/workspace.xml
diff --git a/.idea/.name b/.idea/.name
new file mode 100644
index 0000000..a28d7f5
--- /dev/null
+++ b/.idea/.name
@@ -0,0 +1 @@
+图像风格迁移.py
\ No newline at end of file
diff --git a/.idea/encodings.xml b/.idea/encodings.xml
new file mode 100644
index 0000000..e979dff
--- /dev/null
+++ b/.idea/encodings.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml
new file mode 100644
index 0000000..105ce2d
--- /dev/null
+++ b/.idea/inspectionProfiles/profiles_settings.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/misc.xml b/.idea/misc.xml
new file mode 100644
index 0000000..2a75f48
--- /dev/null
+++ b/.idea/misc.xml
@@ -0,0 +1,7 @@
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/modules.xml b/.idea/modules.xml
new file mode 100644
index 0000000..69bb3a4
--- /dev/null
+++ b/.idea/modules.xml
@@ -0,0 +1,8 @@
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/数字图像处理.iml b/.idea/数字图像处理.iml
new file mode 100644
index 0000000..d0876a7
--- /dev/null
+++ b/.idea/数字图像处理.iml
@@ -0,0 +1,8 @@
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/BGR2GRAY.py b/BGR2GRAY.py
new file mode 100644
index 0000000..af4da09
--- /dev/null
+++ b/BGR2GRAY.py
@@ -0,0 +1,18 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def bgr2gray(img_path):
+ img = cv2.imread(img_path, 1) # 读取图片
+ gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
+ cv2.imwrite('./output/Gray.jpg', gray_image)
+
+
+'''
+输入:彩色图片的地址
+输出:灰度图片
+'''
+if __name__ == '__main__':
+ bgr2gray(sys.argv[1])
diff --git a/Binarization.py b/Binarization.py
new file mode 100644
index 0000000..6cd4efb
--- /dev/null
+++ b/Binarization.py
@@ -0,0 +1,23 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def binarization(img_path, T):
+ img = cv2.imread(img_path, 0) # 读取图片
+ for i in range(0, img.shape[0]):
+ for j in range(0, img.shape[1]):
+ if img[i][j] >= T: # 阈值,可自定义
+ img[i][j] = 255
+ else:
+ img[i][j] = 0
+ cv2.imwrite('./output/binarization.jpg', img)
+
+
+'''
+输入:img_path,阈值
+输出:二值化图片
+'''
+if __name__ == '__main__':
+ binarization(sys.argv[1], eval(sys.argv[2]))
diff --git a/Canny.py b/Canny.py
new file mode 100644
index 0000000..b25640b
--- /dev/null
+++ b/Canny.py
@@ -0,0 +1,22 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def Canny(img_path, low, high):
+ img = cv2.imread(img_path, 0) # 读取图片
+ gradx = cv2.Sobel(img, cv2.CV_16SC1, 1, 0)
+ grady = cv2.Sobel(img, cv2.CV_16SC1, 0, 1)
+
+ # 使用Canny函数处理图像,x,y分别是3求出来的梯度,低阈值50,高阈值150
+ edge_output = cv2.Canny(gradx, grady, low, high)
+ cv2.imwrite('./output/Canny.jpg', edge_output)
+
+
+'''
+输入:一张灰度图 ,低阈值,高阈值
+输出:Canny边缘检测的结果
+'''
+if __name__ == '__main__':
+ Canny(sys.argv[1], eval(sys.argv[2]), eval(sys.argv[3]))
diff --git a/Fourier_transform.py b/Fourier_transform.py
new file mode 100644
index 0000000..7cbfa2f
--- /dev/null
+++ b/Fourier_transform.py
@@ -0,0 +1,24 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def fourier_transform(img_path):
+ img = cv2.imread(img_path, 0)
+ dft = cv2.dft(np.float32(img), flags=cv2.DFT_COMPLEX_OUTPUT)
+ dftShift = np.fft.fftshift(dft)
+ result = 20 * np.log(cv2.magnitude(dftShift[:, :, 0], dftShift[:, :, 1]))
+
+ plt.imshow(result, cmap='gray')
+ plt.title('fft result')
+ plt.axis('off')
+ plt.savefig("./output/fourier_transform.jpg")
+
+
+'''
+输入:一张图片
+输出:傅里叶变换的结果
+'''
+if __name__ == '__main__':
+ fourier_transform(sys.argv[1])
diff --git a/Highpass_filtering.py b/Highpass_filtering.py
new file mode 100644
index 0000000..d16c15e
--- /dev/null
+++ b/Highpass_filtering.py
@@ -0,0 +1,100 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def Highpass_filtering(img_path, type, D0):
+ print(D0)
+ plt.rcParams['font.sans-serif'] = ['SimHei']
+ plt.rcParams['axes.unicode_minus'] = False
+ img = cv2.imread(img_path) # 读取图片
+ b = img[:, :, 0]
+ g = img[:, :, 1]
+ r = img[:, :, 2]
+ pltmod = cv2.merge([r, g, b]) # plt的顺序与cv2不同,显示正确结果需要重新组织顺序
+ # 图片的中心(x,y)
+ m, n = b.shape[0], b.shape[1]
+ x = np.floor(m / 2)
+ y = np.floor(n / 2)
+
+ h = np.zeros((m, n)) # 理想高通滤波器
+ if type == 1:
+ for i in range(m):
+ for j in range(n):
+ D = np.sqrt((i - x) ** 2 + (j - y) ** 2)
+ if D >= D0:
+ h[i, j] = 1
+ else:
+ h[i, j] = 0
+
+ elif type == 2:
+ n0 = 2 # 参数
+ for i in range(m):
+ for j in range(n):
+ D = np.sqrt((i - x) ** 2 + (j - y) ** 2)
+ if D == 0:
+ h[i, j] = 0
+ else:
+ h[i, j] = 1 / (1 + 0.414 * ((D0 / D) ** (2 * n0)))
+
+
+ elif type == 3:
+ n0 = 2 # 参数
+ for i in range(m):
+ for j in range(n):
+ D = np.sqrt((i - x) ** 2 + (j - y) ** 2)
+ if D == 0:
+ h[i, j] = 0
+ else:
+ h[i, j] = np.exp(-0.347 * ((D0 / D) ** n0))
+
+ fb = np.fft.fft2(b)
+ fbshift = np.fft.fftshift(fb)
+ fg = np.fft.fft2(g)
+ fgshift = np.fft.fftshift(fg)
+ fr = np.fft.fft2(r)
+ frshift = np.fft.fftshift(fr)
+
+ fbshift = fbshift * h
+ fgshift = fgshift * h
+ frshift = frshift * h
+
+ ibshift = np.fft.ifftshift(fbshift)
+ ibresult = np.fft.ifft2(ibshift)
+ ibresult = np.uint8(np.abs(ibresult))
+ igshift = np.fft.ifftshift(fgshift)
+ igresult = np.fft.ifft2(igshift)
+ igresult = np.uint8(np.abs(igresult))
+ irshift = np.fft.ifftshift(frshift)
+ irresult = np.fft.ifft2(irshift)
+ irresult = np.uint8(np.abs(irresult))
+
+ result1 = cv2.merge([irresult, igresult, ibresult])
+
+ if type == 1:
+ plt.imshow(result1)
+ plt.title('理想高通滤波')
+ plt.axis('off')
+ plt.savefig('./output/理想高通滤波.jpg')
+ elif type == 2:
+ plt.imshow(result1)
+ plt.title('巴特沃斯高通滤波')
+ plt.axis('off')
+ plt.savefig('./output/巴特沃斯高通滤波.jpg')
+
+ elif type == 3:
+ plt.imshow(result1)
+ plt.title('指数高通滤波')
+ plt.axis('off')
+ plt.savefig('./output/指数高通滤波.jpg')
+
+
+'''
+输入:img_path:图片地址
+ type:滤波器类型(1:理想高通滤波、2:巴特沃斯高通滤波、3:指数高通滤波)
+ D0:阈值
+输出:高通滤波的结果
+'''
+if __name__ == '__main__':
+ Highpass_filtering(sys.argv[1], eval(sys.argv[2]), eval(sys.argv[3]))
diff --git a/HistGraph.py b/HistGraph.py
new file mode 100644
index 0000000..ef39c99
--- /dev/null
+++ b/HistGraph.py
@@ -0,0 +1,24 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def HistGraph(img_path):
+ img = cv2.imread(img_path, 1)
+ color = ["r", "g", "b"] # 每个通道线的颜色
+ # 因为用到cv2函数读取,但是用matplotlib库函数处理,所以应该转BGR格式为RGB格式
+ img = img[:, :, ::-1]
+ for index, c in enumerate(color):
+ hist = cv2.calcHist([img], [index], None, [256], [0, 255])
+ plt.plot(hist, color=c)
+ plt.xlim([0, 255])
+ plt.savefig("./output/HistGraph.jpg")
+
+
+'''
+输入:一张图片
+输出:rgb三通道的灰度直方图
+'''
+if __name__ == '__main__':
+ HistGraph(sys.argv[1])
\ No newline at end of file
diff --git a/HoughLines.py b/HoughLines.py
new file mode 100644
index 0000000..7477c1a
--- /dev/null
+++ b/HoughLines.py
@@ -0,0 +1,22 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def Houghlines(img_path, threshold, minLineLength, maxLineGap):
+ img = cv2.imread(img_path, 1) # 读取图片
+ gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
+ linesP = cv2.HoughLinesP(gray_image, 1, np.pi / 180, threshold, None, minLineLength, maxLineGap)
+ for i_P in linesP:
+ for x1, y1, x2, y2 in i_P:
+ cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 1)
+ cv2.imwrite('./output/HoughLinesP.jpg', img)
+
+
+'''
+输入:一张任意某个边缘提取的结果图片,threshold, minLineLength, maxLineGap
+输出:边缘连接的结果的结果
+'''
+if __name__ == '__main__':
+ Houghlines(sys.argv[1], eval(sys.argv[2]), eval(sys.argv[3]), eval(sys.argv[4]))
diff --git a/Laplacian.py b/Laplacian.py
new file mode 100644
index 0000000..9e88269
--- /dev/null
+++ b/Laplacian.py
@@ -0,0 +1,21 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def laplacian(img_path, ksize):
+ img = cv2.imread(img_path, 0) # 读取图片
+ dst = cv2.Laplacian(img, cv2.CV_16S, ksize)
+
+ # 数据格式转换
+ Laplacian = cv2.convertScaleAbs(dst)
+
+ cv2.imwrite('./output/Laplacian.jpg', Laplacian)
+
+'''
+输入:一张灰度图 ,滤波器大小ksize
+输出:Laplacian边缘检测的结果
+'''
+if __name__ == '__main__':
+ laplacian(sys.argv[1], eval(sys.argv[2]))
diff --git a/Mirror_flip.py b/Mirror_flip.py
new file mode 100644
index 0000000..10c3944
--- /dev/null
+++ b/Mirror_flip.py
@@ -0,0 +1,20 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def mirror_flip(img_path, type):
+ img = cv2.imread(img_path, 1)
+ result = cv2.flip(img, type)
+ cv2.imwrite('./output/mirror_flip.jpg', result)
+
+
+'''
+输入:图片地址,镜像类型(1,0,-1)
+输出:type=1 水平镜像
+ type=0 垂直镜像
+ type=-1 对角镜像
+'''
+if __name__ == '__main__':
+ mirror_flip(sys.argv[1], eval(sys.argv[2]))
\ No newline at end of file
diff --git a/OTSUthreshold.py b/OTSUthreshold.py
new file mode 100644
index 0000000..95ef310
--- /dev/null
+++ b/OTSUthreshold.py
@@ -0,0 +1,21 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def OTSUthreshold(img_path, thresh, maxval):
+ img = cv2.imread(img_path, 0)
+ ret, threshans = cv2.threshold(img, thresh, maxval, type=cv2.THRESH_OTSU)
+ plt.imshow(threshans, cmap='gray')
+ plt.title('OTSUthreshold')
+ plt.axis('off')
+ plt.savefig("./output/OTSUthreshold.jpg")
+
+
+'''
+输入:一张灰度图片(传进彩色图片会被转为灰度图),门限值,结果图片像素的最大值
+输出:OTSU灰度级门限化的结果
+'''
+if __name__ == '__main__':
+ OTSUthreshold(sys.argv[1], eval(sys.argv[2]), eval(sys.argv[3]))
\ No newline at end of file
diff --git a/Prewitt.py b/Prewitt.py
new file mode 100644
index 0000000..89e3868
--- /dev/null
+++ b/Prewitt.py
@@ -0,0 +1,30 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def Prewitt(img_path):
+ img = cv2.imread(img_path, 0) # 读取图片
+ # 边缘检测----Prewitt算子
+ kernelx = np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]], dtype=int)
+ kernely = np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]], dtype=int)
+
+ x = cv2.filter2D(img, cv2.CV_16S, kernelx)
+ y = cv2.filter2D(img, cv2.CV_16S, kernely)
+
+ # 转uint8
+ absX = cv2.convertScaleAbs(x)
+ absY = cv2.convertScaleAbs(y)
+
+ # 加权
+ Prewitt = cv2.addWeighted(absX, 0.5, absY, 0.5, 0)
+
+
+ cv2.imwrite('./output/Prewitt.jpg', Prewitt)
+'''
+输入:一张灰度图
+输出:Prewitt边缘检测的结果
+'''
+if __name__ == '__main__':
+ Prewitt(sys.argv[1])
\ No newline at end of file
diff --git a/Roberts.py b/Roberts.py
new file mode 100644
index 0000000..b48ff9c
--- /dev/null
+++ b/Roberts.py
@@ -0,0 +1,30 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def Roberts(img_path):
+ img = cv2.imread(img_path, 0) # 读取图片
+ kernelx = np.array([[-1, 0], [0, 1]], dtype=int)
+ kernely = np.array([[0, -1], [1, 0]], dtype=int)
+
+ # filter后会有负值,还有会大于255的值。而原图像是uint8,会有截断。因此要使用16位有符号的数据类型,即cv2.CV_16S。
+ x = cv2.filter2D(img, cv2.CV_16S, kernelx)
+ y = cv2.filter2D(img, cv2.CV_16S, kernely)
+
+ # 用convertScaleAbs()函数将其转回原来的uint8形式。否则将无法显示图像,而只是一副灰色的窗口
+ absX = cv2.convertScaleAbs(x)
+ absY = cv2.convertScaleAbs(y)
+
+ # 用cv2.addWeighted(...)函数将其组合起来,其中,alpha是第一幅图片中元素的权重,beta是第二个的权重,gamma是加到最后结果上的一个值。
+ Roberts = cv2.addWeighted(absX, 0.5, absY, 0.5, 0)
+ cv2.imwrite('./output/Roberts.jpg', Roberts)
+
+
+'''
+输入:一张灰度图
+输出:Roberts边缘检测的结果
+'''
+if __name__ == '__main__':
+ Roberts(sys.argv[1])
diff --git a/Sobel.py b/Sobel.py
new file mode 100644
index 0000000..0714d8f
--- /dev/null
+++ b/Sobel.py
@@ -0,0 +1,32 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def Sobel(img_path):
+ img = cv2.imread(img_path, 0) # 读取图片
+ # 边缘检测----Prewitt算子
+ # 边缘检测----Sobel算子
+ # cv2.Sobel(src, ddepth, dx, dy, dst, ksize, scale, delta,borderType)
+ # dx和dy表示的是求导的阶数,0表示这个方向上没有求导
+
+ x = cv2.Sobel(img, cv2.CV_16S, 1, 0)
+ y = cv2.Sobel(img, cv2.CV_16S, 0, 1)
+
+ # 转uint8
+ absX = cv2.convertScaleAbs(x)
+ absY = cv2.convertScaleAbs(y)
+
+ # 加权
+ Sobel = cv2.addWeighted(absX, 0.5, absY, 0.5, 0)
+
+ cv2.imwrite('./output/Sobel.jpg', Sobel)
+
+
+'''
+输入:一张灰度图
+输出:Sobel边缘检测的结果
+'''
+if __name__ == '__main__':
+ Sobel(sys.argv[1])
diff --git a/Split_and_merge.py b/Split_and_merge.py
new file mode 100644
index 0000000..ed985ab
--- /dev/null
+++ b/Split_and_merge.py
@@ -0,0 +1,55 @@
+import sys
+
+import numpy as np
+import cv2
+import matplotlib.pyplot as plt
+
+
+def judge(w0, h0, w, h):
+ a = img[h0: h0 + h, w0: w0 + w]
+ ave = np.mean(a)
+ std = np.std(a, ddof=1)
+ count = 0
+ total = 0
+ for i in range(w0, w0 + w):
+ for j in range(h0, h0 + h):
+ if abs(img[j, i] - ave) < 1 * std:
+ count += 1
+ total += 1
+ if (count / total) < 0.95:
+ return True
+ else:
+ return False
+
+
+def Merge(w0, h0, w, h):
+ for i in range(w0, w0 + w):
+ for j in range(h0, h0 + h):
+ if img[j, i] > 125:
+ img[j, i] = 255
+ else:
+ img[j, i] = 0
+
+
+def function(w0, h0, w, h):
+ if judge(w0, h0, w, h) and (min(w, h) > 5):
+ function(w0, h0, int(w / 2), int(h / 2))
+ function(w0 + int(w / 2), h0, int(w / 2), int(h / 2))
+ function(w0, h0 + int(h / 2), int(w / 2), int(h / 2))
+ function(w0 + int(w / 2), h0 + int(h / 2), int(w / 2), int(h / 2))
+ else:
+ draw(w0, h0, w, h)
+
+
+if __name__ == "__main__":
+ img = cv2.imread(sys.argv[1], 0)
+ img_input = cv2.imread(sys.argv[1], 0)#备份
+
+ height, width = img.shape
+
+ function(0, 0, width, height)
+
+ cv2.imwrite("./output/split_and_merge.jpg",img)
+
+
+
diff --git a/Three-channel.py b/Three-channel.py
new file mode 100644
index 0000000..771d897
--- /dev/null
+++ b/Three-channel.py
@@ -0,0 +1,22 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def three_channel(img_path):
+ img = cv2.imread(img_path, 1) # 读取图片
+ b = img[:, :, 0]
+ g = img[:, :, 1]
+ r = img[:, :, 2]
+ cv2.imwrite('./output/b.jpg', b)
+ cv2.imwrite('./output/g.jpg', g)
+ cv2.imwrite('./output/r.jpg', r)
+
+
+'''
+输入:img_path
+输出:b,g,r三通道共三张图片
+'''
+if __name__ == '__main__':
+ three_channel(sys.argv[1])
diff --git a/add.py b/add.py
new file mode 100644
index 0000000..e7f542b
--- /dev/null
+++ b/add.py
@@ -0,0 +1,19 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def add(img1_path, img2_path):
+ img1 = cv2.imread(img1_path, 1)
+ img2 = cv2.imread(img2_path, 1)
+ result = cv2.add(img1, img2)
+ cv2.imwrite('./output/add.jpg', result)
+
+
+'''
+输入:两张图片(大小相同)
+输出:求和之后的结果
+'''
+if __name__ == '__main__':
+ add(sys.argv[1], sys.argv[2])
diff --git a/circle.py b/circle.py
new file mode 100644
index 0000000..266050b
--- /dev/null
+++ b/circle.py
@@ -0,0 +1,18 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def circle(img_path, center, radius, color, thickness):
+ img = cv2.imread(img_path, 1) # 读取图片
+ cv2.circle(img, center, radius, color, thickness)
+ cv2.imwrite('./output/circle.jpg', img)
+
+
+'''
+输入:img_path, center, radius, color, thickness
+输出:在传入的img上添加一个圆形
+'''
+if __name__ == '__main__':
+ circle(sys.argv[1], eval(sys.argv[2]), eval(sys.argv[3]), eval(sys.argv[4]), eval(sys.argv[5]))
diff --git a/divide.py b/divide.py
new file mode 100644
index 0000000..d20c309
--- /dev/null
+++ b/divide.py
@@ -0,0 +1,19 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def divide(img1_path, img2_path):
+ img1 = cv2.imread(img1_path, 1)
+ img2 = cv2.imread(img2_path, 1)
+ result = cv2.divide(img1, img2)
+ cv2.imwrite('./output/divide.jpg', result)
+
+
+'''
+输入:两张图片(大小相同)
+输出:相除之后的结果
+'''
+if __name__ == '__main__':
+ divide(sys.argv[1], sys.argv[2])
diff --git a/ellipse.py b/ellipse.py
new file mode 100644
index 0000000..92f9101
--- /dev/null
+++ b/ellipse.py
@@ -0,0 +1,18 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def ellipse(img_path, centerCoordinates, axesLength, angle, startAngle, endAngle, color, thickness):
+ img = cv2.imread(img_path, 1) # 读取图片
+ cv2.ellipse(img, centerCoordinates, axesLength, angle, startAngle, endAngle, color, thickness)
+ cv2.imwrite('./output/ellipse.jpg', img)
+
+
+'''
+输入:img_path, centerCoordinates, axesLength, angle, startAngle, endAngle, color, thickness
+输出:在传入的img上添加一个椭圆
+'''
+if __name__ == '__main__':
+ ellipse(sys.argv[1], eval(sys.argv[2]), eval(sys.argv[3]), eval(sys.argv[4]), eval(sys.argv[5]), eval(sys.argv[6]), eval(sys.argv[7]), eval(sys.argv[8]))
diff --git a/equalizeHist.py b/equalizeHist.py
new file mode 100644
index 0000000..c046c16
--- /dev/null
+++ b/equalizeHist.py
@@ -0,0 +1,21 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def equalizeHist(img_path):
+ img = cv2.imread(img_path, 1)
+ r = cv2.equalizeHist(img[:, :, 0])
+ g = cv2.equalizeHist(img[:, :, 1])
+ b = cv2.equalizeHist(img[:, :, 2])
+ res = cv2.merge([r, g, b])
+ cv2.imwrite('./output/equalizeHist.jpg', res)
+
+
+'''
+输入:一张图片
+输出:直方图均衡化的结果
+'''
+if __name__ == '__main__':
+ equalizeHist(sys.argv[1])
\ No newline at end of file
diff --git a/exp_grayscale_transformation.py b/exp_grayscale_transformation.py
new file mode 100644
index 0000000..0459b6e
--- /dev/null
+++ b/exp_grayscale_transformation.py
@@ -0,0 +1,33 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def exp_grayscale_transformation(img, a, b, c):
+ ans = np.zeros((img.shape[0], img.shape[1]))
+ for i in range(img.shape[0]):
+ for j in range(img.shape[1]):
+ ans[i][j] = np.power(b, c * (img[i][j] / 255 - a)) - 1
+ return ans
+
+
+def exp_grayscale_transformation_threeChannel(img_path, a, b, c):
+ img = cv2.imread(img_path, 1)
+ img = np.array(img, dtype=np.float64)
+ # 三个通道分别变换
+ r = exp_grayscale_transformation(img[:, :, 0], a, b, c)
+ g = exp_grayscale_transformation(img[:, :, 1], a, b, c)
+ b = exp_grayscale_transformation(img[:, :, 2], a, b, c)
+ # 三通道合并
+ res = cv2.merge([r, g, b])
+ res = res*255
+ cv2.imwrite('./output/exp_grayscale_transformation.jpg', res)
+
+
+'''
+输入:一张图片,参数a,b,c
+输出:对数灰度变换的结果
+'''
+if __name__ == '__main__':
+ exp_grayscale_transformation_threeChannel(sys.argv[1], eval(sys.argv[2]), eval(sys.argv[3]), eval(sys.argv[4]))
\ No newline at end of file
diff --git a/line.py b/line.py
new file mode 100644
index 0000000..7783dfe
--- /dev/null
+++ b/line.py
@@ -0,0 +1,18 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def line(img_path, pt1, pt2, color, thickness):
+ img = cv2.imread(img_path, 1) # 读取图片
+ cv2.line(img, pt1, pt2, color, thickness)
+ cv2.imwrite('./output/line.jpg', img)
+
+
+'''
+输入:img_path,pt1,pt2,color,thickness
+输出:在传入的img上添加一根直线
+'''
+if __name__ == '__main__':
+ line(sys.argv[1], eval(sys.argv[2]), eval(sys.argv[3]), eval(sys.argv[4]), eval(sys.argv[5]))
diff --git a/linear_grayscale_transformation.py b/linear_grayscale_transformation.py
new file mode 100644
index 0000000..624af3b
--- /dev/null
+++ b/linear_grayscale_transformation.py
@@ -0,0 +1,39 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def linear_grayscale_transformation(img, a, b, c, d):
+ ans = np.zeros((img.shape[0], img.shape[1]))
+ for i in range(img.shape[0]):
+ for j in range(img.shape[1]):
+ if img[i][j] > b:
+ ans[i][j] = d
+ elif a <= img[i][j] <= b:
+ ans[i][j] = (d - c) / (b - a) * (img[i][j] - a) + c
+ else:
+ ans[i][j] = c
+ return ans / 255
+
+
+def linear_grayscale_transformation_threeChannel(img_path, a, b, c, d):
+ img = cv2.imread(img_path, 1)
+ img = np.array(img, dtype=np.float64)
+ # 三个通道分别变换
+ r = linear_grayscale_transformation(img[:, :, 0], a, b, c, d)
+ g = linear_grayscale_transformation(img[:, :, 1], a, b, c, d)
+ b = linear_grayscale_transformation(img[:, :, 2], a, b, c, d)
+ # 三通道合并
+ res = cv2.merge([r, g, b])
+ res = res*255
+ cv2.imwrite('./output/linear_grayscale_transformation.jpg', res)
+
+
+'''
+输入:一张图片,参数a,b,c,d
+输出:线性灰度变换的结果
+'''
+if __name__ == '__main__':
+ linear_grayscale_transformation_threeChannel(sys.argv[1], eval(sys.argv[2]), eval(sys.argv[3]), eval(sys.argv[4]),
+ eval(sys.argv[5]))
diff --git a/log_grayscale_transformation.py b/log_grayscale_transformation.py
new file mode 100644
index 0000000..768cc68
--- /dev/null
+++ b/log_grayscale_transformation.py
@@ -0,0 +1,33 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def log_grayscale_transformation(img, a, b, c):
+ ans = np.zeros((img.shape[0], img.shape[1]))
+ for i in range(img.shape[0]):
+ for j in range(img.shape[1]):
+ ans[i][j] = a + np.log(img[i][j] + 1) / (b * np.log(c))
+ return ans
+
+
+def log_grayscale_transformation_threeChannel(img_path, a, b, c):
+ img = cv2.imread(img_path, 1)
+ img = np.array(img, dtype=np.float64)
+ # 三个通道分别变换
+ r = log_grayscale_transformation(img[:, :, 0], a, b, c)
+ g = log_grayscale_transformation(img[:, :, 1], a, b, c)
+ b = log_grayscale_transformation(img[:, :, 2], a, b, c)
+ # 三通道合并
+ res = cv2.merge([r, g, b])
+ res = res*255
+ cv2.imwrite('./output/log_grayscale_transformation.jpg', res)
+
+
+'''
+输入:一张图片,参数a,b,c
+输出:对数灰度变换的结果
+'''
+if __name__ == '__main__':
+ log_grayscale_transformation_threeChannel(sys.argv[1], eval(sys.argv[2]), eval(sys.argv[3]), eval(sys.argv[4]))
diff --git a/multiply.py b/multiply.py
new file mode 100644
index 0000000..c61a4db
--- /dev/null
+++ b/multiply.py
@@ -0,0 +1,19 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def multiply(img1_path, img2_path):
+ img1 = cv2.imread(img1_path, 1)
+ img2 = cv2.imread(img2_path, 1)
+ result = cv2.multiply(img1, img2)
+ cv2.imwrite('./output/multiply.jpg', result)
+
+
+'''
+输入:两张图片(大小相同)
+输出:相乘之后的结果
+'''
+if __name__ == '__main__':
+ multiply(sys.argv[1], sys.argv[2])
diff --git a/output/Anti_sharpening_masking.jpg b/output/Anti_sharpening_masking.jpg
new file mode 100644
index 0000000..ed54f14
Binary files /dev/null and b/output/Anti_sharpening_masking.jpg differ
diff --git a/output/Canny.jpg b/output/Canny.jpg
new file mode 100644
index 0000000..be652bf
Binary files /dev/null and b/output/Canny.jpg differ
diff --git a/output/Differentiation.jpg b/output/Differentiation.jpg
new file mode 100644
index 0000000..feba6ad
Binary files /dev/null and b/output/Differentiation.jpg differ
diff --git a/output/Digital_morphology.jpg b/output/Digital_morphology.jpg
new file mode 100644
index 0000000..044dcb7
Binary files /dev/null and b/output/Digital_morphology.jpg differ
diff --git a/output/GaussianBlur_filter.jpg b/output/GaussianBlur_filter.jpg
new file mode 100644
index 0000000..11aedd4
Binary files /dev/null and b/output/GaussianBlur_filter.jpg differ
diff --git a/output/Gaussian_noisy.jpg b/output/Gaussian_noisy.jpg
new file mode 100644
index 0000000..c1e9310
Binary files /dev/null and b/output/Gaussian_noisy.jpg differ
diff --git a/output/Gray.jpg b/output/Gray.jpg
new file mode 100644
index 0000000..b895e47
Binary files /dev/null and b/output/Gray.jpg differ
diff --git a/output/HistGraph.jpg b/output/HistGraph.jpg
new file mode 100644
index 0000000..f9b46b6
Binary files /dev/null and b/output/HistGraph.jpg differ
diff --git a/output/HoughLinesP.jpg b/output/HoughLinesP.jpg
new file mode 100644
index 0000000..c86295f
Binary files /dev/null and b/output/HoughLinesP.jpg differ
diff --git a/output/Laplacian.jpg b/output/Laplacian.jpg
new file mode 100644
index 0000000..ecd8d1a
Binary files /dev/null and b/output/Laplacian.jpg differ
diff --git a/output/OTSUthreshold.jpg b/output/OTSUthreshold.jpg
new file mode 100644
index 0000000..b64bc73
Binary files /dev/null and b/output/OTSUthreshold.jpg differ
diff --git a/output/Prewitt.jpg b/output/Prewitt.jpg
new file mode 100644
index 0000000..d9d8e48
Binary files /dev/null and b/output/Prewitt.jpg differ
diff --git a/output/Roberts.jpg b/output/Roberts.jpg
new file mode 100644
index 0000000..1258477
Binary files /dev/null and b/output/Roberts.jpg differ
diff --git a/output/Sobel.jpg b/output/Sobel.jpg
new file mode 100644
index 0000000..ad27acb
Binary files /dev/null and b/output/Sobel.jpg differ
diff --git a/output/add.jpg b/output/add.jpg
new file mode 100644
index 0000000..af25345
Binary files /dev/null and b/output/add.jpg differ
diff --git a/output/b.jpg b/output/b.jpg
new file mode 100644
index 0000000..05fc488
Binary files /dev/null and b/output/b.jpg differ
diff --git a/output/binarization.jpg b/output/binarization.jpg
new file mode 100644
index 0000000..d056435
Binary files /dev/null and b/output/binarization.jpg differ
diff --git a/output/circle.jpg b/output/circle.jpg
new file mode 100644
index 0000000..c629920
Binary files /dev/null and b/output/circle.jpg differ
diff --git a/output/clock.jpg b/output/clock.jpg
new file mode 100644
index 0000000..be09624
Binary files /dev/null and b/output/clock.jpg differ
diff --git a/output/edge.jpg b/output/edge.jpg
new file mode 100644
index 0000000..df121da
Binary files /dev/null and b/output/edge.jpg differ
diff --git a/output/ellipse.jpg b/output/ellipse.jpg
new file mode 100644
index 0000000..c629920
Binary files /dev/null and b/output/ellipse.jpg differ
diff --git a/output/equalizeHist.jpg b/output/equalizeHist.jpg
new file mode 100644
index 0000000..34e8491
Binary files /dev/null and b/output/equalizeHist.jpg differ
diff --git a/output/exp_grayscale_transformation.jpg b/output/exp_grayscale_transformation.jpg
new file mode 100644
index 0000000..2aa3949
Binary files /dev/null and b/output/exp_grayscale_transformation.jpg differ
diff --git a/output/fourier_transform.jpg b/output/fourier_transform.jpg
new file mode 100644
index 0000000..828d854
Binary files /dev/null and b/output/fourier_transform.jpg differ
diff --git a/output/g.jpg b/output/g.jpg
new file mode 100644
index 0000000..83a06c1
Binary files /dev/null and b/output/g.jpg differ
diff --git a/output/line.jpg b/output/line.jpg
new file mode 100644
index 0000000..f809a8b
Binary files /dev/null and b/output/line.jpg differ
diff --git a/output/linear_grayscale_transformation.jpg b/output/linear_grayscale_transformation.jpg
new file mode 100644
index 0000000..09a76e1
Binary files /dev/null and b/output/linear_grayscale_transformation.jpg differ
diff --git a/output/log_grayscale_transformation.jpg b/output/log_grayscale_transformation.jpg
new file mode 100644
index 0000000..d8b2c65
Binary files /dev/null and b/output/log_grayscale_transformation.jpg differ
diff --git a/output/mid1.jpg b/output/mid1.jpg
new file mode 100644
index 0000000..8c33c94
Binary files /dev/null and b/output/mid1.jpg differ
diff --git a/output/mid2.jpg b/output/mid2.jpg
new file mode 100644
index 0000000..47bf319
Binary files /dev/null and b/output/mid2.jpg differ
diff --git a/output/mid3.jpg b/output/mid3.jpg
new file mode 100644
index 0000000..0c954d8
Binary files /dev/null and b/output/mid3.jpg differ
diff --git a/output/mid4.jpg b/output/mid4.jpg
new file mode 100644
index 0000000..df121da
Binary files /dev/null and b/output/mid4.jpg differ
diff --git a/output/mirror_flip.jpg b/output/mirror_flip.jpg
new file mode 100644
index 0000000..5cfe026
Binary files /dev/null and b/output/mirror_flip.jpg differ
diff --git a/output/multiply.jpg b/output/multiply.jpg
new file mode 100644
index 0000000..c07cdf7
Binary files /dev/null and b/output/multiply.jpg differ
diff --git a/output/polylines.jpg b/output/polylines.jpg
new file mode 100644
index 0000000..7208fe7
Binary files /dev/null and b/output/polylines.jpg differ
diff --git a/output/putText.jpg b/output/putText.jpg
new file mode 100644
index 0000000..8e1b454
Binary files /dev/null and b/output/putText.jpg differ
diff --git a/output/r.jpg b/output/r.jpg
new file mode 100644
index 0000000..9b6e671
Binary files /dev/null and b/output/r.jpg differ
diff --git a/output/rectangle.jpg b/output/rectangle.jpg
new file mode 100644
index 0000000..ab99672
Binary files /dev/null and b/output/rectangle.jpg differ
diff --git a/output/regionGrow.jpg b/output/regionGrow.jpg
new file mode 100644
index 0000000..eb0406e
Binary files /dev/null and b/output/regionGrow.jpg differ
diff --git a/output/reshape.jpg b/output/reshape.jpg
new file mode 100644
index 0000000..27700bd
Binary files /dev/null and b/output/reshape.jpg differ
diff --git a/output/rotate.jpg b/output/rotate.jpg
new file mode 100644
index 0000000..1f15ac2
Binary files /dev/null and b/output/rotate.jpg differ
diff --git a/output/saltnoisy.jpg b/output/saltnoisy.jpg
new file mode 100644
index 0000000..5042a0d
Binary files /dev/null and b/output/saltnoisy.jpg differ
diff --git a/output/split_and_merge.jpg b/output/split_and_merge.jpg
new file mode 100644
index 0000000..5209eb6
Binary files /dev/null and b/output/split_and_merge.jpg differ
diff --git a/output/style_change_result.jpg b/output/style_change_result.jpg
new file mode 100644
index 0000000..ce40dad
Binary files /dev/null and b/output/style_change_result.jpg differ
diff --git a/output/template_matching.jpg b/output/template_matching.jpg
new file mode 100644
index 0000000..0a547be
Binary files /dev/null and b/output/template_matching.jpg differ
diff --git a/output/time.txt b/output/time.txt
new file mode 100644
index 0000000..16f8ebc
--- /dev/null
+++ b/output/time.txt
@@ -0,0 +1 @@
+ʶʱΪ: 11:20:40
\ No newline at end of file
diff --git a/output/translate.jpg b/output/translate.jpg
new file mode 100644
index 0000000..c7586c8
Binary files /dev/null and b/output/translate.jpg differ
diff --git a/output/warpAffine.jpg b/output/warpAffine.jpg
new file mode 100644
index 0000000..c131893
Binary files /dev/null and b/output/warpAffine.jpg differ
diff --git a/output/zoom.jpg b/output/zoom.jpg
new file mode 100644
index 0000000..d93cc0e
Binary files /dev/null and b/output/zoom.jpg differ
diff --git a/output/巴特沃斯高通滤波.jpg b/output/巴特沃斯高通滤波.jpg
new file mode 100644
index 0000000..b07c36d
Binary files /dev/null and b/output/巴特沃斯高通滤波.jpg differ
diff --git a/output/指数高通滤波.jpg b/output/指数高通滤波.jpg
new file mode 100644
index 0000000..d6b389b
Binary files /dev/null and b/output/指数高通滤波.jpg differ
diff --git a/output/理想高通滤波.jpg b/output/理想高通滤波.jpg
new file mode 100644
index 0000000..6c3711d
Binary files /dev/null and b/output/理想高通滤波.jpg differ
diff --git a/pictures/aniya.jpg b/pictures/aniya.jpg
new file mode 100644
index 0000000..1a45680
Binary files /dev/null and b/pictures/aniya.jpg differ
diff --git a/pictures/cat.jpg b/pictures/cat.jpg
new file mode 100644
index 0000000..c0087d0
Binary files /dev/null and b/pictures/cat.jpg differ
diff --git a/pictures/clock.jpg b/pictures/clock.jpg
new file mode 100644
index 0000000..0cf4b85
Binary files /dev/null and b/pictures/clock.jpg differ
diff --git a/pictures/clock1.jpg b/pictures/clock1.jpg
new file mode 100644
index 0000000..f638d69
Binary files /dev/null and b/pictures/clock1.jpg differ
diff --git a/pictures/clock2.jpg b/pictures/clock2.jpg
new file mode 100644
index 0000000..5702a46
Binary files /dev/null and b/pictures/clock2.jpg differ
diff --git a/pictures/clock3.jpg b/pictures/clock3.jpg
new file mode 100644
index 0000000..5bf6b16
Binary files /dev/null and b/pictures/clock3.jpg differ
diff --git a/pictures/clock4.jpg b/pictures/clock4.jpg
new file mode 100644
index 0000000..2f36bc2
Binary files /dev/null and b/pictures/clock4.jpg differ
diff --git a/pictures/clock5.jpg b/pictures/clock5.jpg
new file mode 100644
index 0000000..d330520
Binary files /dev/null and b/pictures/clock5.jpg differ
diff --git a/pictures/content.jpg b/pictures/content.jpg
new file mode 100644
index 0000000..b07df10
Binary files /dev/null and b/pictures/content.jpg differ
diff --git a/pictures/countryside.jpg b/pictures/countryside.jpg
new file mode 100644
index 0000000..c2279c5
Binary files /dev/null and b/pictures/countryside.jpg differ
diff --git a/pictures/dog.jpg b/pictures/dog.jpg
new file mode 100644
index 0000000..2e8cdb8
Binary files /dev/null and b/pictures/dog.jpg differ
diff --git a/pictures/dragon.jpg b/pictures/dragon.jpg
new file mode 100644
index 0000000..c993db7
Binary files /dev/null and b/pictures/dragon.jpg differ
diff --git a/pictures/egg.jpg b/pictures/egg.jpg
new file mode 100644
index 0000000..88ba440
Binary files /dev/null and b/pictures/egg.jpg differ
diff --git a/pictures/eye.jpg b/pictures/eye.jpg
new file mode 100644
index 0000000..43abfdb
Binary files /dev/null and b/pictures/eye.jpg differ
diff --git a/pictures/hello.jpg b/pictures/hello.jpg
new file mode 100644
index 0000000..f781daa
Binary files /dev/null and b/pictures/hello.jpg differ
diff --git a/pictures/kazike.jpg b/pictures/kazike.jpg
new file mode 100644
index 0000000..add09fd
Binary files /dev/null and b/pictures/kazike.jpg differ
diff --git a/pictures/love.jpg b/pictures/love.jpg
new file mode 100644
index 0000000..294c507
Binary files /dev/null and b/pictures/love.jpg differ
diff --git a/pictures/minzi.jpg b/pictures/minzi.jpg
new file mode 100644
index 0000000..b395f1b
Binary files /dev/null and b/pictures/minzi.jpg differ
diff --git a/pictures/moon.jpg b/pictures/moon.jpg
new file mode 100644
index 0000000..d6e5b2a
Binary files /dev/null and b/pictures/moon.jpg differ
diff --git a/pictures/saien.jpg b/pictures/saien.jpg
new file mode 100644
index 0000000..41320d5
Binary files /dev/null and b/pictures/saien.jpg differ
diff --git a/pictures/sheep.jpg b/pictures/sheep.jpg
new file mode 100644
index 0000000..bed3d5b
Binary files /dev/null and b/pictures/sheep.jpg differ
diff --git a/pictures/star.jpg b/pictures/star.jpg
new file mode 100644
index 0000000..7fa06ca
Binary files /dev/null and b/pictures/star.jpg differ
diff --git a/pictures/star_part.jpg b/pictures/star_part.jpg
new file mode 100644
index 0000000..6c064aa
Binary files /dev/null and b/pictures/star_part.jpg differ
diff --git a/pictures/style.jpg b/pictures/style.jpg
new file mode 100644
index 0000000..88a8563
Binary files /dev/null and b/pictures/style.jpg differ
diff --git a/pictures/yao.jpg b/pictures/yao.jpg
new file mode 100644
index 0000000..cd1044e
Binary files /dev/null and b/pictures/yao.jpg differ
diff --git a/pictures/yellowcat.jpg b/pictures/yellowcat.jpg
new file mode 100644
index 0000000..dfbf4f4
Binary files /dev/null and b/pictures/yellowcat.jpg differ
diff --git a/pictures/zhilang.jpg b/pictures/zhilang.jpg
new file mode 100644
index 0000000..b5247a1
Binary files /dev/null and b/pictures/zhilang.jpg differ
diff --git a/ploylines.py b/ploylines.py
new file mode 100644
index 0000000..1dfb330
--- /dev/null
+++ b/ploylines.py
@@ -0,0 +1,20 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def polylines(img_path, data, isClosed, color, thickness):
+ img = cv2.imread(img_path, 1) # 读取图片
+ pts = np.array(data, np.int32)
+ pts = pts.reshape((-1, 1, 2))
+ cv2.polylines(img, [pts], isClosed, color, thickness)
+ cv2.imwrite('./output/polylines.jpg', img)
+
+
+'''
+输入:img_path, pts, isClosed, color, thickness
+输出:在传入的img上添加一个多边形
+'''
+if __name__ == '__main__':
+ polylines(sys.argv[1], eval(sys.argv[2]), eval(sys.argv[3]), eval(sys.argv[4]), eval(sys.argv[5]))
diff --git a/putText.py b/putText.py
new file mode 100644
index 0000000..834cb1e
--- /dev/null
+++ b/putText.py
@@ -0,0 +1,18 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def putText(img_path, text, org, fontFace, fontScale, color, thickness=None, lineType=None):
+ img = cv2.imread(img_path, 1) # 读取图片
+ cv2.putText(img, text, org, fontFace, fontScale, color, thickness, lineType)
+ cv2.imwrite('./output/putText.jpg', img)
+
+
+'''
+输入:img_path, text, org, fontFace, fontScale, color, thickness, lineType
+输出:在传入的img上添加一行文字
+'''
+if __name__ == '__main__':
+ putText(sys.argv[1], sys.argv[2], eval(sys.argv[3]), eval(sys.argv[4]), eval(sys.argv[5]), eval(sys.argv[6]), eval(sys.argv[7]), eval(sys.argv[8]))
diff --git a/rectangle.py b/rectangle.py
new file mode 100644
index 0000000..34a9f4d
--- /dev/null
+++ b/rectangle.py
@@ -0,0 +1,18 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def rectangle(img_path, pt1, pt2, color, thickness):
+ img = cv2.imread(img_path, 1) # 读取图片
+ cv2.rectangle(img, pt1, pt2, color, thickness)
+ cv2.imwrite('./output/rectangle.jpg', img)
+
+
+'''
+输入:img_path,pt1,pt2,color,thickness
+输出:在传入的img上添加一个矩形
+'''
+if __name__ == '__main__':
+ rectangle(sys.argv[1], eval(sys.argv[2]), eval(sys.argv[3]), eval(sys.argv[4]), eval(sys.argv[5]))
diff --git a/regionGrow.py b/regionGrow.py
new file mode 100644
index 0000000..b9284d8
--- /dev/null
+++ b/regionGrow.py
@@ -0,0 +1,63 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+class Point(object):
+ def __init__(self, x, y):
+ self.x = x
+ self.y = y
+
+ def getX(self):
+ return self.x
+
+ def getY(self):
+ return self.y
+
+
+def getGrayDiff(img, currentPoint, tmpPoint): # 获得两点像素之差的绝对值
+ return abs(int(img[currentPoint.x, currentPoint.y]) - int(img[tmpPoint.x, tmpPoint.y]))
+
+
+def selectConnects(p): # 8邻域或者4邻域
+ if p != 0:
+ connects = [Point(-1, -1), Point(0, -1), Point(1, -1), Point(1, 0), Point(1, 1), \
+ Point(0, 1), Point(-1, 1), Point(-1, 0)]
+ else:
+ connects = [Point(0, -1), Point(1, 0), Point(0, 1), Point(-1, 0)]
+ return connects
+
+
+def regionGrow(img_path, x, y, thresh, p):
+ img = cv2.imread(img_path, 0) # 读取图片
+ height, weight = img.shape
+ seedMark = np.zeros(img.shape)
+ seedList = []
+ seedList.append(Point(x, y))
+ label = 1
+ connects = selectConnects(p)
+ while (len(seedList) > 0):
+ currentPoint = seedList.pop(0)
+
+ seedMark[currentPoint.x, currentPoint.y] = label
+ for i in range(len(connects)):
+ tmpX = currentPoint.x + connects[i].x
+ tmpY = currentPoint.y + connects[i].y
+ if tmpX < 0 or tmpY < 0 or tmpX >= height or tmpY >= weight:
+ continue
+ grayDiff = getGrayDiff(img, currentPoint, Point(tmpX, tmpY))
+ if grayDiff < thresh and seedMark[tmpX, tmpY] == 0:
+ seedMark[tmpX, tmpY] = label
+ seedList.append(Point(tmpX, tmpY))
+ cv2.imwrite('./output/regionGrow.jpg', seedMark*255)
+
+'''
+输入:img_path:图片地址
+ seeds:初始种子,是一个元素类型为Point的列表,如[ Point(0, -1), Point(1, 0),Point(0, 1), Point(-1, 0)]
+ thresh:门限值,两个坐标像素值小于thresh归为一类
+ p:等于0算法基于四领域,等于1算法基于八领域
+输出:二值图片,白色部分为初始种子所生长出来的区域,黑色为另一区域
+'''
+if __name__ == '__main__':
+ regionGrow(sys.argv[1], eval(sys.argv[2]), eval(sys.argv[3]), eval(sys.argv[4]), eval(sys.argv[5]))
diff --git a/resize.py b/resize.py
new file mode 100644
index 0000000..00f50fc
--- /dev/null
+++ b/resize.py
@@ -0,0 +1,19 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def resize(img_path, shape):
+ img = cv2.imread(img_path, 1)
+ img = cv2.resize(img, shape)
+ cv2.imwrite('./output/reshape.jpg', img)
+
+
+'''
+输入:一张图片,图片大小
+输出:对应大小的图片
+'''
+if __name__ == '__main__':
+ resize(sys.argv[1], eval(sys.argv[2]))
+
diff --git a/rotate.py b/rotate.py
new file mode 100644
index 0000000..12e9f68
--- /dev/null
+++ b/rotate.py
@@ -0,0 +1,19 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def rotate(img_path, center, angle, scale):
+ img = cv2.imread(img_path, 1)
+ M = cv2.getRotationMatrix2D(center, angle, scale) # 使用内置函数构建矩阵
+ result = cv2.warpAffine(img, M, (img.shape[1], img.shape[0]))
+ cv2.imwrite('./output/rotate.jpg', result)
+
+
+'''
+输入:一张图片,旋转中心,旋转角
+输出:旋转后的图片
+'''
+if __name__ == '__main__':
+ rotate(sys.argv[1], eval(sys.argv[2]), eval(sys.argv[3]), eval(sys.argv[4]))
diff --git a/subtract.py b/subtract.py
new file mode 100644
index 0000000..8819682
--- /dev/null
+++ b/subtract.py
@@ -0,0 +1,19 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def subtract(img1_path, img2_path):
+ img1 = cv2.imread(img1_path, 1)
+ img2 = cv2.imread(img2_path, 1)
+ result = cv2.subtract(img1, img2)
+ cv2.imwrite('./output/subtract.jpg', result)
+
+
+'''
+输入:两张图片(大小相同)
+输出:相减之后的结果
+'''
+if __name__ == '__main__':
+ subtract(sys.argv[1], sys.argv[2])
\ No newline at end of file
diff --git a/template_matching.py b/template_matching.py
new file mode 100644
index 0000000..1b9bdb3
--- /dev/null
+++ b/template_matching.py
@@ -0,0 +1,27 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def template_matching(img_path, tmp_path):
+ img = cv2.imread(img_path) # 读取图片
+ img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
+ img_part = cv2.imread(tmp_path, 0) # 读取图片
+
+ w, h = img_part.shape[::-1]
+ # 使用cv2.TM_CCOEFF_NORMED相关性系数匹配方法时,最佳匹配结果在值等于1处,最差匹配结果在值等于-1处,值等于0直接表示二者不相关。
+ res = cv2.matchTemplate(img_gray, img_part, cv2.TM_CCOEFF_NORMED)
+ min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
+ top_left = max_loc # 最大值即为最佳匹配点
+ bottom_right = (top_left[0] + w, top_left[1] + h)
+ cv2.rectangle(img, top_left, bottom_right, 255, 2) # 绘制矩形
+ cv2.imwrite('./output/template_matching.jpg', img)
+
+
+'''
+输入:目标图片,匹配模板图片
+输出:在目标图片标注出模版图片出现的位置
+'''
+if __name__ == '__main__':
+ template_matching(sys.argv[1], sys.argv[2])
diff --git a/test.py b/test.py
new file mode 100644
index 0000000..614ecac
--- /dev/null
+++ b/test.py
@@ -0,0 +1,4 @@
+import os
+
+if __name__ == '__main__':
+ os.system("python line.py ./pictures/saien.jpg (1200,100) (456,400) (255,255,0) 20")
diff --git a/translation.py b/translation.py
new file mode 100644
index 0000000..76b8788
--- /dev/null
+++ b/translation.py
@@ -0,0 +1,19 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def translate(img_path, x, y):
+ img = cv2.imread(img_path, 1)
+ M = np.float32([[1, 0, x], [0, 1, y]])
+ result = cv2.warpAffine(img, M, (img.shape[1], img.shape[0]))
+ cv2.imwrite('./output/translate.jpg', result)
+
+
+'''
+输入:一张图片,x方向移动数值,y方向移动数值
+输出:平移后的图片
+'''
+if __name__ == '__main__':
+ translate(sys.argv[1], eval(sys.argv[2]), eval(sys.argv[3]))
diff --git a/warpAffine.py b/warpAffine.py
new file mode 100644
index 0000000..1eefa99
--- /dev/null
+++ b/warpAffine.py
@@ -0,0 +1,20 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def warpAffine(img_path, matSrc, matDst):
+ img = cv2.imread(img_path, 1)
+ height, width = img.shape[:2]
+ M = cv2.getAffineTransform(np.float32(matSrc), np.float32(matDst)) # 生成矩阵
+ result = cv2.warpAffine(img, M, (width, height))
+ cv2.imwrite('./output/warpAffine.jpg', result)
+
+
+'''
+输入:一张图片,旋转前三个点的坐标matSrc,旋转后三个点的坐标matDst
+输出:仿射变换后的图片
+'''
+if __name__ == '__main__':
+ warpAffine(sys.argv[1], eval(sys.argv[2]), eval(sys.argv[3]))
diff --git a/zoom.py b/zoom.py
new file mode 100644
index 0000000..645fc9e
--- /dev/null
+++ b/zoom.py
@@ -0,0 +1,19 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def zoom(img_path, x, y):
+ img = cv2.imread(img_path, 1)
+ M = np.float32([[x, 0, 0], [0, y, 0]]) # 图片宽变为原来的x倍,高变为原来的y倍
+ result = cv2.warpAffine(img, M, (img.shape[1], img.shape[0]))
+ cv2.imwrite('./output/zoom.jpg', result)
+
+
+'''
+输入:一张图片,宽度缩放比例,高度缩放比例
+输出:缩放后的图片
+'''
+if __name__ == '__main__':
+ zoom(sys.argv[1], eval(sys.argv[2]), eval(sys.argv[3]))
\ No newline at end of file
diff --git a/去噪滤波器集合.py b/去噪滤波器集合.py
new file mode 100644
index 0000000..893333c
--- /dev/null
+++ b/去噪滤波器集合.py
@@ -0,0 +1,92 @@
+import sys
+import random
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def Arithmetic_mean_filtering(img_path):
+ img = cv2.imread(img_path,0) # 读取图片
+ result1 = np.zeros(img.shape, np.uint8)
+ # 算数均值滤波
+ for i in range(img.shape[0]):
+ for j in range(img.shape[1]):
+ sum = 0
+ for m in range(-1, 2):
+ for n in range(-1, 2):
+ if 0 <= i + m < img.shape[0] and 0 <= j + n < img.shape[1]:
+ # 像素值求和
+ sum += img[i + m][j + n]
+ result1[i][j] = (sum / 9).astype(np.int32)
+
+ cv2.imwrite('./output/Arithmetic_mean_filtering.jpg', result1)
+
+
+def Maximum_mean_filtering(img_path):
+ img = cv2.imread(img_path,0) # 读取图片
+ result = np.zeros(img.shape, np.uint8)
+ # 最大值滤波器
+ for i in range(img.shape[0]):
+ for j in range(img.shape[1]):
+ # 最大值滤波器
+ max_ = 0
+ for m in range(-1, 2):
+ for n in range(-1, 2):
+ if 0 <= i + m < img.shape[0] and 0 <= j + n < img.shape[1]:
+ # 通过比较判断是否需要更新最大值
+ if img[i + m][j + n] > max_:
+ # 更新最大值
+ max_ = img[i + m][j + n]
+ result[i][j] = max_
+
+ cv2.imwrite('./output/Maximum_filter.jpg', result)
+
+
+def GaussianBlur_filtering(img_path):
+ img = cv2.imread(img_path) # 读取图片
+ blur = cv2.GaussianBlur(img, (5, 5), 0, 0)
+ cv2.imwrite('./output/GaussianBlur_filter.jpg', blur)
+
+
+def medianBlur_filtering(img_path):
+ img = cv2.imread(img_path) # 读取图片
+ median = cv2.medianBlur(img, 5)
+ cv2.imwrite('./output/median_filter.jpg', median)
+
+
+def Geometric_mean_filtering(img_path):
+ img = cv2.imread(img_path,0) # 读取图片
+ result1 = np.zeros(img.shape, np.uint8)
+ # 几何均值滤波
+ for i in range(img.shape[0]):
+ for j in range(img.shape[1]):
+ ji = 1.0
+ for m in range(-1, 2):
+ for n in range(-1, 2):
+ if 0 <= i + m < img.shape[0] and 0 <= j + n < img.shape[1]:
+ ji = ji * img[i + m][j + n]
+ result1[i][j] = pow(ji, 1 / 9)
+
+ cv2.imwrite('./output/Geometric_mean_filtering.jpg', result1)
+
+
+def filtering(img_path, type):
+ if type == 1:
+ Arithmetic_mean_filtering(img_path)
+ elif type == 2:
+ Geometric_mean_filtering(img_path)
+ elif type == 3:
+ Maximum_mean_filtering(img_path)
+ elif type == 4:
+ GaussianBlur_filtering(img_path)
+ elif type == 5:
+ medianBlur_filtering(img_path)
+
+
+'''
+输入:img_path:添加了噪声的图片
+ type:滤波种类
+输出:滤波的结果
+'''
+if __name__ == '__main__':
+ filtering(sys.argv[1], eval(sys.argv[2]))
\ No newline at end of file
diff --git a/反锐化掩膜法.py b/反锐化掩膜法.py
new file mode 100644
index 0000000..70f215a
--- /dev/null
+++ b/反锐化掩膜法.py
@@ -0,0 +1,34 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def Anti_sharpening_masking(img_path):
+ img = cv2.imread(img_path, 0) # 读取图片
+ m, n = img.shape[0], img.shape[1]
+
+ # 利用局部平均法得到人为模糊后的的图像res
+ kernel = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]], dtype=int)
+ res = cv2.filter2D(img, cv2.CV_16S, kernel) / 9
+ res = cv2.convertScaleAbs(res)
+
+ ans = np.zeros((m, n), dtype=np.int32)
+
+ for i in range(m):
+ for j in range(n):
+ ans[i, j] = int(img[i, j]) + 9 * (int(img[i, j]) - int(res[i, j]))
+ if ans[i, j] > 255:
+ ans[i, j] = 255
+ elif ans[i][j] < 0:
+ ans[i, j] = 0
+
+ cv2.imwrite('./output/Anti_sharpening_masking.jpg', ans)
+
+
+'''
+输入:img_path:图片地址
+输出:反锐化掩膜法的结果
+'''
+if __name__ == '__main__':
+ Anti_sharpening_masking(sys.argv[1])
diff --git a/图像风格迁移.py b/图像风格迁移.py
new file mode 100644
index 0000000..3d313f1
--- /dev/null
+++ b/图像风格迁移.py
@@ -0,0 +1,254 @@
+from __future__ import print_function
+
+import sys
+
+import numpy
+import cv2
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import torch.optim as optim
+
+from PIL import Image
+import matplotlib.pyplot as plt
+
+import torchvision.transforms as transforms
+import torchvision.models as models
+
+import copy
+
+from torch.autograd._functions import tensor
+
+
+def style_change(style_img_path, content_img_path):
+ # 选择要运行代码的设备,torch.cuda相较于cpu拥有更佳的运行速度
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
+ # 图像大小(读入后都转换为imsize*imsize大小的图片)
+ imsize = 512 if torch.cuda.is_available() else 128
+ # 用于转换读入图片的大小,并将图片转换为张量(tensor)
+ loader = transforms.Compose([
+ transforms.Resize([imsize, imsize]),
+ transforms.ToTensor()])
+
+ # 加载图片
+ def image_loader(image_name):
+ image = Image.open(image_name)
+ image = loader(image).unsqueeze(0)
+ return image.to(device, torch.float)
+
+ # 读入风格图片和内容图片
+ style_img = image_loader(style_img_path)
+ content_img = image_loader(content_img_path)
+
+ # 判断风格图片和内容图片大小是否一致
+ assert style_img.size() == content_img.size(), \
+ "we need to import style and content images of the same size"
+
+ # load的逆操作,用于将tensor转化为图片
+ unloader = transforms.ToPILImage()
+
+ # plt的动态绘图模式
+ plt.ion()
+
+ # 打印图片,传入一个tensor后unload成图片并打印
+ def imshow(tensor, title=None):
+ image = tensor.cpu().clone()
+ image = image.squeeze(0)
+ image = unloader(image)
+ image = image.resize((1024, 1024))
+ plt.imshow(image)
+ if title is not None:
+ plt.title(title)
+ plt.pause(0.001)
+
+ # plt.figure()
+ # imshow(style_img, title='Style Image')
+ #
+ # plt.figure()
+ # imshow(content_img, title='Content Image')
+
+ # 计算输入图片与内容图片之间差异的损失函数
+ class ContentLoss(nn.Module):
+
+ def __init__(self, target, ):
+ super(ContentLoss, self).__init__()
+ self.target = target.detach()
+
+ def forward(self, input):
+ # 使用torch中定义好的均方差损失函数
+ self.loss = F.mse_loss(input, self.target)
+ return input
+
+ # 计算输入的gram矩阵
+ def gram_matrix(input):
+ a, b, c, d = input.size() # 对于一张图片,a为1,b为卷积核数量,c、d为图片宽和高
+ features = input.view(a * b, c * d)
+ # gram矩阵即为features乘以features的转置
+ G = torch.mm(features, features.t())
+ return G.div(a * b * c * d)
+
+ # 利用上面的gram矩阵,计算输入图片与风格图片之间差异的损失函数
+ class StyleLoss(nn.Module):
+
+ def __init__(self, target_feature):
+ super(StyleLoss, self).__init__()
+ self.target = gram_matrix(target_feature).detach()
+
+ def forward(self, input):
+ G = gram_matrix(input)
+ self.loss = F.mse_loss(G, self.target)
+ return input
+
+ # 预定义好的VGG19卷积神经网络
+ cnn = models.vgg19(pretrained=True).features.to(device).eval()
+ # 归一化平均值和方差
+ cnn_normalization_mean = torch.tensor([0.485, 0.456, 0.406]).to(device)
+ cnn_normalization_std = torch.tensor([0.229, 0.224, 0.225]).to(device)
+
+ # 创建一个模块来规范化输入图像,以便轻松地将其放入模型进行训练
+ class Normalization(nn.Module):
+ def __init__(self, mean, std):
+ super(Normalization, self).__init__()
+ self.mean = torch.tensor(mean).view(-1, 1, 1)
+ self.std = torch.tensor(std).view(-1, 1, 1)
+
+ def forward(self, img):
+ # normalize img
+ return (img - self.mean) / self.std
+
+ # 使用输入图像与内容图像的conv_4层结果来计算损失
+ content_layers_default = ['conv_4']
+ # 使用输入图像与风格图像的以下五层结果来计算损失
+ style_layers_default = ['conv_1', 'conv_2', 'conv_3', 'conv_4', 'conv_5']
+
+ # 计算损失
+ def get_style_model_and_losses(cnn, normalization_mean, normalization_std,
+ style_img, content_img,
+ content_layers=content_layers_default,
+ style_layers=style_layers_default):
+ # 模型归一化
+ normalization = Normalization(normalization_mean, normalization_std).to(device)
+ # 损失值
+ content_losses = []
+ style_losses = []
+
+ model = nn.Sequential(normalization)
+
+ i = 0 # 记录卷积层的数量
+
+ # 为每一层命名,便于通过名字拿到每一层的结果
+ for layer in cnn.children():
+ if isinstance(layer, nn.Conv2d):
+ i += 1
+ name = 'conv_{}'.format(i)
+ elif isinstance(layer, nn.ReLU):
+ name = 'relu_{}'.format(i)
+ layer = nn.ReLU(inplace=False)
+ elif isinstance(layer, nn.MaxPool2d):
+ name = 'pool_{}'.format(i)
+ elif isinstance(layer, nn.BatchNorm2d):
+ name = 'bn_{}'.format(i)
+ else:
+ raise RuntimeError('Unrecognized layer: {}'.format(layer.__class__.__name__))
+
+ model.add_module(name, layer)
+ # 使用输入图像与内容图像的conv_4层结果来计算损失
+ if name in content_layers:
+ target = model(content_img).detach()
+ content_loss = ContentLoss(target)
+ model.add_module("content_loss_{}".format(i), content_loss)
+ content_losses.append(content_loss)
+ # 使用输入图像与风格图像的对应层结果来计算损失
+ if name in style_layers:
+ target_feature = model(style_img).detach()
+ style_loss = StyleLoss(target_feature)
+ model.add_module("style_loss_{}".format(i), style_loss)
+ style_losses.append(style_loss)
+
+ for i in range(len(model) - 1, -1, -1):
+ if isinstance(model[i], ContentLoss) or isinstance(model[i], StyleLoss):
+ break
+
+ model = model[:(i + 1)]
+
+ return model, style_losses, content_losses
+
+ input_img = content_img.clone()
+ # plt.figure()
+ # imshow(input_img, title='Input Image')
+
+ # 得到优化器
+ def get_input_optimizer(input_img):
+ optimizer = optim.LBFGS([input_img])
+ return optimizer
+
+ def run_style_transfer(cnn, normalization_mean, normalization_std,
+ content_img, style_img, input_img, num_steps=200,
+ style_weight=1000000, content_weight=1):
+ print('Building the style transfer model..')
+ model, style_losses, content_losses = get_style_model_and_losses(cnn,
+ normalization_mean, normalization_std,
+ style_img, content_img)
+
+ # 优化输入图片而不是模型参数,所以需要更新所有的requires_grad字段
+ input_img.requires_grad_(True)
+ model.requires_grad_(False)
+
+ optimizer = get_input_optimizer(input_img)
+
+ print('Optimizing..')
+ # 训练迭代次数
+ run = [0]
+ while run[0] <= num_steps:
+
+ def closure():
+ with torch.no_grad():
+ input_img.clamp_(0, 1)
+
+ optimizer.zero_grad()
+ model(input_img)
+ style_score = 0
+ content_score = 0
+
+ for sl in style_losses:
+ style_score += sl.loss
+ for cl in content_losses:
+ content_score += cl.loss
+
+ style_score *= style_weight
+ content_score *= content_weight
+
+ loss = style_score + content_score
+ # 根据损失值反馈
+ loss.backward()
+
+ run[0] += 1
+ # 每训练50次输出损失值
+ if run[0] % 10 == 0:
+ print("run {}:".format(run))
+ print('Style Loss : {:4f} Content Loss: {:4f}'.format(
+ style_score.item(), content_score.item()))
+ print()
+
+ return style_score + content_score
+
+ optimizer.step(closure)
+
+ with torch.no_grad():
+ input_img.clamp_(0, 1)
+
+ return input_img
+
+ output = run_style_transfer(cnn, cnn_normalization_mean, cnn_normalization_std,
+ content_img, style_img, input_img)
+
+ plt.figure()
+ imshow(output, title='Output Image')
+ plt.savefig("./output/style_change_result.jpg")
+ # sphinx_gallery_thumbnail_number = 4
+ # plt.ioff()
+ # plt.show()
+
+
+if __name__ == "__main__":
+ style_change(sys.argv[1], sys.argv[2])
diff --git a/微分法.py b/微分法.py
new file mode 100644
index 0000000..536f656
--- /dev/null
+++ b/微分法.py
@@ -0,0 +1,41 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def Differentiation(img_path, T):
+ img = cv2.imread(img_path,0) # 读取图片
+ m, n = img.shape[0], img.shape[1]
+
+ ans = np.zeros((m, n), dtype=np.uint8)
+
+ kernelx = np.array([[-1, 0], [0, 1]], dtype=int)
+ kernely = np.array([[0, -1], [1, 0]], dtype=int)
+
+ x = cv2.filter2D(img, cv2.CV_16S, kernelx)
+ y = cv2.filter2D(img, cv2.CV_16S, kernely)
+
+ absX = cv2.convertScaleAbs(x)
+ absY = cv2.convertScaleAbs(y)
+
+ Roberts = cv2.addWeighted(absX, 0.5, absY, 0.5, 0)
+
+ # 背景保留
+ for i in range(m):
+ for j in range(n):
+ if Roberts[i, j] >= T:
+ ans[i, j] = Roberts[i, j]
+ else:
+ ans[i, j] = img[i, j]
+
+ cv2.imwrite('./output/Differentiation.jpg', ans)
+
+
+'''
+输入:img_path:图片地址
+ T:阈值
+输出:微分法的结果
+'''
+if __name__ == '__main__':
+ Differentiation(sys.argv[1], eval(sys.argv[2]))
diff --git a/数字形态学.py b/数字形态学.py
new file mode 100644
index 0000000..5a2db6d
--- /dev/null
+++ b/数字形态学.py
@@ -0,0 +1,39 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+'''
+形态学操作
+cv2.morphologyEx(src, op, kernel)
+src:输入图像,即源图像;
+op: 表示形态学运算的类型,有以下几个可选项
+MORPH_ERODE:“腐蚀”;
+MORPH_DILATE:“膨胀”;
+MORPH_OPEN:开运算;
+MORPH_CLOSE:闭运算;
+MORPH_TOPHAT:“顶帽” f(top) = f - f(open) ;
+MORPH_BLACKHAT:“黑帽”“底帽” f(black) = f(close) - f ;
+MORPH_GRADIENT:形态学梯度 f(grad) = f(dilate) - f(erode) ;
+kernel:形态学运算的内核。若为NULL时,表示的是默认使用参考点位于中心3 x 3的核。
+
+'''
+
+
+def Digital_morphology(img_path, type, shape, size):
+ kernel = cv2.getStructuringElement(shape, size, (-1, -1)) # 5x5交叉结构元
+ img = cv2.imread(img_path) # 读取图片
+ res = cv2.morphologyEx(img, type, kernel)
+ cv2.imwrite('./output/Digital_morphology.jpg', res)
+
+
+'''
+输入:img_path:图片地址
+ type:形态学操作类型,见上方注释,直接传入CV2.xxx的字符串
+ shape:结构元形状,cv2.MORPH_RECT; cv2.MORPH_CROSS; cv2.MORPH_ELLIPSE; 分别对应矩形结构元、交叉形结构元和椭圆形结构元。
+ size:结构元大小,例如(5,5)
+输出:数字形态学操作的结果
+'''
+if __name__ == '__main__':
+ Digital_morphology(sys.argv[1], eval(sys.argv[2]), eval(sys.argv[3]), eval(sys.argv[4]))
+
diff --git a/时钟识别.py b/时钟识别.py
new file mode 100644
index 0000000..15f616f
--- /dev/null
+++ b/时钟识别.py
@@ -0,0 +1,149 @@
+import sys
+import random
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def clock_identify(img_path):
+ clock = cv2.imread(img_path, 1) # 读取图片
+
+ # 0、高斯滤波去噪
+ clock = cv2.GaussianBlur(clock, (5, 5), 0, 0)
+ cv2.imwrite('./output/mid1.jpg', clock)
+ # 1、灰度化
+ GrayImage = cv2.cvtColor(clock, cv2.COLOR_BGR2GRAY)
+ cv2.imwrite('./output/mid2.jpg', GrayImage)
+ # 2、Roberts边缘提取
+ kernelx = np.array([[-1, 0], [0, 1]], dtype=int)
+ kernely = np.array([[0, -1], [1, 0]], dtype=int)
+ x = cv2.filter2D(GrayImage, cv2.CV_16S, kernelx)
+ y = cv2.filter2D(GrayImage, cv2.CV_16S, kernely)
+ absX = cv2.convertScaleAbs(x)
+ absY = cv2.convertScaleAbs(y)
+ Roberts = cv2.addWeighted(absX, 0.5, absY, 0.5, 0)
+ cv2.imwrite('./output/mid3.jpg', Roberts)
+ # 3、二值化
+ for i in range(0, Roberts.shape[0]):
+ for j in range(0, Roberts.shape[1]):
+ if Roberts[i][j] >= 30:
+ Roberts[i][j] = 255
+ else:
+ Roberts[i][j] = 0
+ cv2.imwrite('./output/mid4.jpg', Roberts)
+ # 4、霍夫直线检测
+ linesP = cv2.HoughLinesP(image=Roberts, rho=1, theta=np.pi / 180, threshold=150, minLineLength=clock.shape[0] / 6,
+ maxLineGap=10) # (在canny边缘检测的结果上进行边缘链接)
+
+ for i_P in linesP:
+ for x1, y1, x2, y2 in i_P:
+ cv2.line(clock, (x1, y1), (x2, y2), (0, 0, 255), 3)
+
+ # 5、霍夫圆检测
+ circlesP = cv2.HoughCircles(image=Roberts, method=cv2.HOUGH_GRADIENT, dp=2, minDist=500, param1=100, param2=100,
+ minRadius=200, maxRadius=500)
+ circlesP = circlesP.reshape(-1, 3)
+ circlesP = np.uint16(np.around(circlesP))
+
+ print(circlesP)
+ for i in circlesP:
+ cv2.circle(clock, (i[0], i[1]), i[2], (0, 0, 255), 5) # 画圆
+ cv2.imwrite('./output/clock.jpg', clock)
+ cv2.imwrite('./output/edge.jpg', Roberts)
+
+ def getDist(point1, point2):
+ return np.sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2)
+
+ def angle(v1, v2):
+ cosvalue = (v1[0] * v2[0] + v1[1] * v2[1]) / (
+ np.sqrt(v1[0] ** 2 + v1[1] ** 2) * np.sqrt(v2[0] ** 2 + v2[1] ** 2))
+ return np.arccos(cosvalue)
+
+ def isSimilar(line1, line2, center):
+ nearpoint1 = [line1[0], line1[1]]
+ farpoint1 = [line1[2], line1[3]]
+ nearpoint2 = [line2[0], line2[1]]
+ farpoint2 = [line2[2], line2[3]]
+ if getDist(nearpoint1, center) > getDist(farpoint1, center):
+ nearpoint1, farpoint1 = farpoint1, nearpoint1
+ if getDist(nearpoint2, center) > getDist(farpoint2, center):
+ nearpoint2, farpoint2 = farpoint2, nearpoint2
+ vector1 = [farpoint1[0] - nearpoint1[0], farpoint1[1] - nearpoint1[1]]
+ vector2 = [farpoint2[0] - nearpoint2[0], farpoint2[1] - nearpoint2[1]]
+ if angle(vector1, vector2) < 0.09:
+ return True
+ else:
+ return False
+
+ line_group = [[], [], []]
+ center = [circlesP[0][0], circlesP[0][1]]
+ print(center)
+ for i_P in linesP:
+ for group in line_group:
+ if len(group) == 0:
+ group.append(i_P[0])
+ break
+ else:
+ if (isSimilar(i_P[0], group[0], center)):
+ group.append(i_P[0])
+ break
+
+ for group in line_group:
+ for line in group:
+ print(line)
+ print("--------------")
+
+ def getAvgLength(group):
+ ans = 0
+ for line in group:
+ ans = ans + getDist([line[0], line[1]], [line[2], line[3]])
+ return ans / len(group)
+
+ def getAngle(line):
+ nearpoint = [line[0], line[1]]
+ farpoint = [line[2], line[3]]
+ if getDist(nearpoint, center) > getDist(farpoint, center):
+ nearpoint, farpoint = farpoint, nearpoint
+ vector = [farpoint[0] - nearpoint[0], farpoint[1] - nearpoint[1]]
+ if vector[0] == 0 and vector[1] > 0:
+ return np.pi
+ if vector[0] > 0 and vector[1] > 0:
+ return np.pi / 2 + np.arctan(vector[1] / vector[0])
+ if vector[0] > 0 and vector[1] == 0:
+ return np.pi / 2
+ if vector[0] > 0 and vector[1] < 0:
+ return np.arctan(vector[0] / (-vector[1]))
+ if vector[0] == 0 and vector[1] < 0:
+ return 0
+ if vector[0] < 0 and vector[1] < 0:
+ return 2 * np.pi - np.arctan((-vector[0]) / (-vector[1]))
+ if vector[0] < 0 and vector[1] == 0:
+ return 1.5 * np.pi
+ if vector[0] < 0 and vector[1] > 0:
+ return np.pi + np.arctan((-vector[0]) / vector[1])
+
+ class pointer:
+ def __init__(self, group):
+ self.length = getAvgLength(group)
+ self.angle = getAngle(group[0])
+
+ clockhands = []
+ for group in line_group:
+ clockhands.append(pointer(group))
+
+ clockhands.sort(key=lambda x: x.length)
+
+ hour = (clockhands[0].angle / (2 * np.pi)) * 12
+ minites = (clockhands[1].angle / (2 * np.pi)) * 60
+ seconds = (clockhands[2].angle / (2 * np.pi)) * 60
+ seconds = int(seconds)
+ minites = int(minites)
+ hour = int(hour)
+
+ with open('./output/time.txt', 'w') as f:
+ f.write("识别出来的时间为: " + str(hour) + ":" + str(minites) + ":" + str(seconds))
+ f.close()
+
+
+if __name__ == '__main__':
+ clock_identify(sys.argv[1])
\ No newline at end of file
diff --git a/添加噪声.py b/添加噪声.py
new file mode 100644
index 0000000..eb9a28e
--- /dev/null
+++ b/添加噪声.py
@@ -0,0 +1,52 @@
+import sys
+import random
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def addNoisy(img_path, type, para1, para2):
+ img = cv2.imread(img_path) # 读取图片
+ out = np.zeros(img.shape, np.uint8)
+ if type == 1:
+ # 添加高斯噪声-------------------------------------------------------
+ # 将图片的像素值归一化,存入矩阵中
+ img = np.array(img / 255, dtype=float)
+ # 生成正态分布的噪声,其中0表示均值,0.1表示方差
+ noise = np.random.normal(para1, para2, img.shape) # 参数:正态分布的均值和方差,可自定义
+ # 将噪声叠加到图片上
+ out = img + noise
+ # 将图像的归一化像素值控制在0和1之间,防止噪声越界
+ out = np.clip(out, 0.0, 1.0)
+ # 将图像的像素值恢复到0到255之间
+ out = np.uint8(out * 255)
+ cv2.imwrite('./output/Gaussian_noisy.jpg', out)
+ elif type == 2:
+ # 添加椒盐噪声--------------------------------------------------------
+ # 遍历图像,获取叠加噪声后的图像
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
+ for i in range(img.shape[0]):
+ for j in range(img.shape[1]):
+ rdn = random.random()
+ if rdn < para1:
+ # 添加椒噪声
+ out[i][j] = 0
+ elif rdn > para2:
+ # 添加盐噪声
+ out[i][j] = 255
+ else:
+ # 不添加噪声
+ out[i][j] = img[i][j]
+ cv2.imwrite('./output/saltnoisy.jpg', out)
+
+
+'''
+输入:img_path:图片地址
+ type:噪声类型(1为高斯噪声,2为椒盐噪声)
+ para1,para2:如果添加的是高斯噪声,para1为正态分布均值,para2为正态分布方差
+ 如果添加的是椒盐噪声,para1为添加椒噪声阈值,para2为添加盐噪声阈值
+
+输出:添加了噪声的图片
+'''
+if __name__ == '__main__':
+ addNoisy(sys.argv[1], eval(sys.argv[2]), eval(sys.argv[3]), eval(sys.argv[4]))
diff --git a/边缘检测合集.py b/边缘检测合集.py
new file mode 100644
index 0000000..0d43955
--- /dev/null
+++ b/边缘检测合集.py
@@ -0,0 +1,102 @@
+import sys
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def Roberts(img_path):
+ img = cv2.imread(img_path, 0) # 读取图片
+ kernelx = np.array([[-1, 0], [0, 1]], dtype=int)
+ kernely = np.array([[0, -1], [1, 0]], dtype=int)
+
+ # filter后会有负值,还有会大于255的值。而原图像是uint8,会有截断。因此要使用16位有符号的数据类型,即cv2.CV_16S。
+ x = cv2.filter2D(img, cv2.CV_16S, kernelx)
+ y = cv2.filter2D(img, cv2.CV_16S, kernely)
+
+ # 用convertScaleAbs()函数将其转回原来的uint8形式。否则将无法显示图像,而只是一副灰色的窗口
+ absX = cv2.convertScaleAbs(x)
+ absY = cv2.convertScaleAbs(y)
+
+ # 用cv2.addWeighted(...)函数将其组合起来,其中,alpha是第一幅图片中元素的权重,beta是第二个的权重,gamma是加到最后结果上的一个值。
+ Roberts = cv2.addWeighted(absX, 0.5, absY, 0.5, 0)
+ cv2.imwrite('./output/Roberts.jpg', Roberts)
+
+
+def laplacian(img_path, ksize):
+ img = cv2.imread(img_path, 0) # 读取图片
+ dst = cv2.Laplacian(img, cv2.CV_16S, ksize)
+
+ # 数据格式转换
+ Laplacian = cv2.convertScaleAbs(dst)
+
+ cv2.imwrite('./output/Laplacian.jpg', Laplacian)
+
+
+def Prewitt(img_path):
+ img = cv2.imread(img_path, 0) # 读取图片
+ # 边缘检测----Prewitt算子
+ kernelx = np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]], dtype=int)
+ kernely = np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]], dtype=int)
+
+ x = cv2.filter2D(img, cv2.CV_16S, kernelx)
+ y = cv2.filter2D(img, cv2.CV_16S, kernely)
+
+ # 转uint8
+ absX = cv2.convertScaleAbs(x)
+ absY = cv2.convertScaleAbs(y)
+
+ # 加权
+ Prewitt = cv2.addWeighted(absX, 0.5, absY, 0.5, 0)
+
+ cv2.imwrite('./output/Prewitt.jpg', Prewitt)
+
+
+def Sobel(img_path):
+ img = cv2.imread(img_path, 0) # 读取图片
+ # 边缘检测----Prewitt算子
+ # 边缘检测----Sobel算子
+ # cv2.Sobel(src, ddepth, dx, dy, dst, ksize, scale, delta,borderType)
+ # dx和dy表示的是求导的阶数,0表示这个方向上没有求导
+
+ x = cv2.Sobel(img, cv2.CV_16S, 1, 0)
+ y = cv2.Sobel(img, cv2.CV_16S, 0, 1)
+
+ # 转uint8
+ absX = cv2.convertScaleAbs(x)
+ absY = cv2.convertScaleAbs(y)
+
+ # 加权
+ Sobel = cv2.addWeighted(absX, 0.5, absY, 0.5, 0)
+
+ cv2.imwrite('./output/Sobel.jpg', Sobel)
+
+
+def Canny(img_path, low, high):
+ img = cv2.imread(img_path, 0) # 读取图片
+ gradx = cv2.Sobel(img, cv2.CV_16SC1, 1, 0)
+ grady = cv2.Sobel(img, cv2.CV_16SC1, 0, 1)
+
+ # 使用Canny函数处理图像,x,y分别是3求出来的梯度,低阈值50,高阈值150
+ edge_output = cv2.Canny(gradx, grady, low, high)
+ cv2.imwrite('./output/Canny.jpg', edge_output)
+
+
+def edge_detect(img_path, type):
+ if type == 1:
+ Roberts(img_path)
+ elif type == 2:
+ laplacian(img_path, 3)
+ elif type == 3:
+ Prewitt(img_path)
+ elif type == 4:
+ Sobel(img_path)
+ elif type == 5:
+ Canny(img_path, 0, 255)
+
+
+'''
+输入:一张灰度图 ,类型type
+输出:边缘检测的结果
+'''
+if __name__ == '__main__':
+ edge_detect(sys.argv[1], eval(sys.argv[2]))