18、OpenCV Python 简单实现一个图片生成(类似抖音生成字母人像)

 1 __author__ = "WSX"
 2 import cv2 as cv
 3 import numpy as np
 4 
 5 def local_threshold(img):  #局部阈值
 6     gray = cv.cvtColor(img , cv.COLOR_BGR2GRAY)  #首先变为灰度图
 7     binary = cv.adaptiveThreshold( gray ,255 , cv.ADAPTIVE_THRESH_GAUSSIAN_C , cv.THRESH_BINARY, 25 , 10,)#255 最大值
 8     #上面的 有两种方法ADAPTIVE_THRESH_GAUSSIAN_C (带权重的均值)和ADAPTIVE_THRESH_MEAN_C(和均值比较)
 9     #blockSize 必须为奇数 ,c为常量(每个像素块均值 和均值比较 大的多余c。。。少于c)
10     #ret 阈值 , binary二值化图像
11     cv.imshow("binary", binary)
12     return binary
13 
14 def jinzita( level ,img ):
15     temp = img.copy()
16     level = level
17     pyr_img = []
18     for i in range(level):
19         dst = cv.pyrDown( temp )  #pyrup 和pyrDown 相反
20         temp = dst.copy()
21     return temp
22 
23 def result(binary):
24     w , h = binary.shape[:2]
25     print(binary)
26     print(w,h)
27     # temp = np.zeros((w ,h))
28     # temp = list(temp)
29     #temp = []; tt = []
30     with open("result.txt","r+") as f:
31         for i in range(w):
32             for j in range(h):
33                 if binary[i,j] == 0:
34                     temp = "0"
35                 elif binary[i,j] == 255:
36                     temp = "1"
37                 f.write(temp)
38             f.write("\r\n")
39         f.close()
40     #print(temp.shape)
41 def main():
42     img = cv.imread("1.JPG")
43     #cv.namedWindow("Show", cv.WINDOW_AUTOSIZE)
44     cv.imshow("Show", img)
45     t = jinzita(3, img)
46     binary=local_threshold(t)
47     result(binary)
48     cv.waitKey(0)
49     cv.destroyAllWindows()
50 
51 main()

猜你喜欢

转载自www.cnblogs.com/WSX1994/p/9161703.html