import cv2
import numpy as np
# 灰度化讀取圖片
image = cv2.imreade('number.jpg',0)
# 將圖片二值化
retval, img = cv2.threshold(image,170,255,cv2.THRESH_BINAPY_INV)
# 創(chuàng)建一個空白圖片(img.shape[0]為height,img.shape[1]為width)
paintx = np.zeros(img.shape,np.uint8)
# 將新圖像數(shù)組中的所有通道元素的值都設(shè)置為0
cv2.cv.Zero(cv2.cv.fromarray(paintx))
# 創(chuàng)建width長度都為0的數(shù)組
w = [0]*image.shape[1]
# 對每一行計算投影值
for x in range(image.shape[1]):
for y in range(image.shape[0]):
t = cv2.cv.Get2D(cv2.cv.fromarray(img),y,x)
if t[0] == 0:
w[x] += 1
# 繪制垂直投影圖
for x in range(image.shape[1]):
for y in range(w[x]):
# 把為0的像素變成白
cv2.cv.Set2D(cv2.cv.fromarray(paintx),y,x(255,255,255,0))
# 顯示圖片
cv2.imshow('paintx',paintx)
cv2.waitKey(0)
另外把水平投影也一起寫了
painty = np.zeros(img.shape,np.uint8)
cv2.cv.Zero(cv2.cv.fromarray(painty))
h = [0]*image.shape[0]
for y in range(image.shape[0]):
for x in range(image.shape[1]):
s = cv2.cv.Get2D(cv2.cv.fromarray(img),y,x)
if s[0] == 0:
h[y] += 1
for y in range(image.shape(0)):
for x in range(h[y]):
cv2.cv.Set2D(cv2.cv.fromarray(painty),y,x,(255,255,255,0))
cv2.imshow('painty',painty)
cv2.waitKey(0)