gpt4 book ai didi

python - 计算图像中的绿色百分比

转载 作者:行者123 更新时间:2023-12-01 00:53:39 25 4
gpt4 key购买 nike

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

我通过迭代图像中的每个像素并检查每个像素的颜色来进行计算。最后,我记录绿色像素的数量并找到整个图像中的总百分比。

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 万张图像。如何优化代码?

最佳答案

假设 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 个循环)

关于python - 计算图像中的绿色百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56387361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com