Python + OpenCV 直接上代碼
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
import cv2 import numpy as np from matplotlib import pyplot as plt from PIL import Image img = cv2.imread( '0002.jpg' ) #讀取圖片,裝換為可運(yùn)算的數(shù)組 GrayImage = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #將BGR圖轉(zhuǎn)為灰度圖 ret,thresh1 = cv2.threshold(GrayImage, 130 , 255 ,cv2.THRESH_BINARY) #將圖片進(jìn)行二值化(130,255)之間的點(diǎn)均變?yōu)?55(背景) # print(thresh1[0,0])#250 輸出[0,0]這個(gè)點(diǎn)的像素值 #返回值ret為閾值 # print(ret)#130 (h,w) = thresh1.shape #返回高和寬 # print(h,w)#s輸出高和寬 a = [ 0 for z in range ( 0 , w)] print (a) #a = [0,0,0,0,0,0,0,0,0,0,...,0,0]初始化一個(gè)長(zhǎng)度為w的數(shù)組,用于記錄每一列的黑點(diǎn)個(gè)數(shù) #記錄每一列的波峰 for j in range ( 0 ,w): #遍歷一列 for i in range ( 0 ,h): #遍歷一行 if thresh1[i,j] = = 0 : #如果改點(diǎn)為黑點(diǎn) a[j] + = 1 #該列的計(jì)數(shù)器加一計(jì)數(shù) thresh1[i,j] = 255 #記錄完后將其變?yōu)榘咨? # print (j) # for j in range ( 0 ,w): #遍歷每一列 for i in range ((h - a[j]),h): #從該列應(yīng)該變黑的最頂部的點(diǎn)開(kāi)始向最底部涂黑 thresh1[i,j] = 0 #涂黑 #此時(shí)的thresh1便是一張圖像向垂直方向上投影的直方圖 #如果要分割字符的話,其實(shí)并不需要把這張圖給畫(huà)出來(lái),只需要的到a=[]即可得到想要的信息 # img2 =Image.open('0002.jpg') # img2.convert('L') # img_1 = np.array(img2) plt.imshow(thresh1,cmap = plt.gray()) plt.show() cv2.imshow( 'img' ,thresh1) cv2.waitKey( 0 ) cv2.destroyAllWindows() |
原圖:
運(yùn)行結(jié)果:
在水平方向上進(jìn)行投影,代碼如下所示(原理同上):
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
26
|
import cv2 import numpy as np from matplotlib import pyplot as plt from PIL import Image img = cv2.imread( 'C:/Users/Jet Zhang/Desktop/50/50/cut.png' ) GrayImage = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) ret,thresh1 = cv2.threshold(GrayImage, 130 , 255 ,cv2.THRESH_BINARY) (h,w) = thresh1.shape #返回高和寬 a = [ 0 for z in range ( 0 , h)] print (a) for j in range ( 0 ,h): for i in range ( 0 ,w): if thresh1[j,i] = = 0 : a[j] + = 1 thresh1[j,i] = 255 for j in range ( 0 ,h): for i in range ( 0 ,a[j]): thresh1[j,i] = 0 plt.imshow(thresh1,cmap = plt.gray()) plt.show() |
效果圖如下所示:
以上這篇Python實(shí)現(xiàn)圖像的垂直投影示例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/qq_37053885/article/details/79248986