首页 > 解决方案 > 计算图像中的绿色百分比

问题描述

我想计算图像中的绿色百分比

我通过遍历图像中的每个像素并检查每个像素的颜色来计算。最后,我保留绿色像素的数量并找到整个图像中的总百分比。

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 毫秒;我想处理 100 万张图像。如何优化代码?

标签: pythonpython-3.ximage-processing

解决方案


假设 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 毫秒 ± 6.24 毫秒(平均值 ± 标准偏差。7 次运行,每次 10 次循环)

矢量化版本

每个循环 461 µs ± 78.2 µs(7 次运行的平均值 ± 标准偏差,每次 1000 个循环)


推荐阅读