python 对图片做垂直投影
Python 对图片做垂直投影
本文利用opencv对图片进行垂直投影,做出垂直投影图,大体思路:打开图片,灰度化,二值化,按列进行统计,新建一个大小和原图一样的图片,按列进行填充:
- cv2.cv.Get2D(cv2.cv.fromarray(img), y, x) 获取物理坐标为(y,x)处的灰度值
- cv2.cv.Set2D(cv2.cv.fromarray(img), y, x,(255, 255, 255)) 设置某一位置处rgb值
实现
例如:
# -*-coding:utf-8-*-
import cv2
import numpy as np
# 灰度化读取图片
image = cv2.imread('10.bmp', 0)
# cv2.imshow('aa',image)
# cv2.waitKey(0)
# 将图片二值化
retval, img = cv2.threshold(image, 170, 255, cv2.THRESH_BINARY_INV)
# cv2.imshow('aa',img)
# cv2.waitKey(0)
# 创建一个空白图片(img.shape[0]为height,img.shape[1]为width)
paintx = np.zeros(img.shape, np.uint8)
# 将新图像数组中的所有通道元素的值都设置为0
cv2.cv.Zero(cv2.cv.fromarray(paintx))
# 创建width长度都为0的数组
w = [0] * image.shape[1]
print w
# 对每一行计算投影值
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))
# 显示图片
cv2.namedWindow('image', cv2.WINDOW_NORMAL)
cv2.imshow('image',paintx)
cv2.imwrite('image.jpg',paintx)
cv2.waitKey(0)