我要计算图像中的绿色百分比
我已经通过迭代图像中的每个像素并检查每个像素的颜色进行了计算。最后,我保留绿色像素数的计数,并找到整个图像中的总百分比。
def green_color_optimized(screenpath):
start_time = time.time()
img = image.load_img(screenpath,target_size=(300,300,3))
x = image.img_to_array(img)
print("Image size: ", x.shape)
count_green = 0
for i in range(0,x.shape[0]):
for j in range(0,x.shape[1]):
pixel = list(map(int, x[i,j].tolist()))
if sum(pixel) != 0:
green_pixel = 100*(pixel[1]/sum(pixel))
blue_pixel = 100*(pixel[2]/sum(pixel))
red_pixel = 100*(pixel[0]/sum(pixel))
if green_pixel > red_pixel and green_pixel > blue_pixel:
if green_pixel > 35:
count_green += 1
green_percent = round(100*(count_green/(x.shape[0]*x.shape[1])),2)
使用此代码,每个图像大约需要200毫秒的处理时间;我想处理一百万张图像如何优化代码?
答案 0 :(得分:2)
假设x是一个numpy数组,则应始终向量化矩阵运算。以下代码的运行速度快约200倍:
# Your original function, with the file i/o removed for timing comparison
def green_original(x):
count_green = 0
for i in range(0,x.shape[0]):
for j in range(0,x.shape[1]):
pixel = list(map(int, x[i,j].tolist()))
if sum(pixel) != 0:
green_pixel = 100*(pixel[1]/sum(pixel))
blue_pixel = 100*(pixel[2]/sum(pixel))
red_pixel = 100*(pixel[0]/sum(pixel))
if green_pixel > red_pixel and green_pixel > blue_pixel:
if green_pixel > 35:
count_green += 1
green_percent = round(100*(count_green/(x.shape[0]*x.shape[1])),2)
return green_percent
def green_vectorized(x):
mask = (img[:,:,1] > img[:,:,0]) & (img[:,:,1] > img[:,:,2]) & ((img[:,:,1]/np.sum(img, axis=2)) > .35)
round(100 * np.sum(mask)/(x.shape[0]*x.shape[1]), 2)
img = np.ones(shape=(300,300,3))
img[0:150,0:150, 1] = 134
%timeit green_original(img)
%timeit green_vectorized(img)
每个循环81.7 ms±6.24 ms(平均±标准偏差,共运行7次,每个循环10个)
每个循环461 µs±78.2 µs(平均±标准偏差,共运行7次,每个循环1000个)