问题
如图所示,如何快速获取图像中这条横线的bounding box的值,以及如何获取这条直线中所有黑色像素的数目呢?
解决方法
最简单的方法就是直接遍历图像中每个像素,判断每个像素是否为黑色,然后获取bounding box的值以及所有黑色像素的数目,但是这种方法非常耗时(C++与opencv搭档时可以使用指针快速的遍历,但是python这样做就很耗时),下面介绍一种更快的方法,以及实验对比
#coding=utf-8
import numpy as np
import cv2
import time
img = cv2.imread('test.png')
img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
print img.shape
min_x = img.shape[0]
min_y = img.shape[1]
max_x = 0
max_y = 0
#像素挨个遍历
t1 = time.clock()
for i in range(img.shape[0]):
for j in range(img.shape[1]):
if img[i][j] < 255:
if i < min_x:
min_x = i
if j < min_y:
min_y = j
if i > max_x: