python - 计算图像中的绿色百分比
问题描述
我想计算图像中的绿色百分比
我通过遍历图像中的每个像素并检查每个像素的颜色来计算。最后,我保留绿色像素的数量并找到整个图像中的总百分比。
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 毫秒 ± 6.24 毫秒(平均值 ± 标准偏差。7 次运行,每次 10 次循环)
矢量化版本
每个循环 461 µs ± 78.2 µs(7 次运行的平均值 ± 标准偏差,每次 1000 个循环)
推荐阅读
- google-bigquery - 从转换的 lon 和 lat 数据到 geojson 缺少“类型”:特征、“几何”
- node.js - GroupBy 聚合,包括 mongo 中的缺失日期
- sql - 加入3个表不正确的结果
- c# - 如何使用自动映射器添加现有实体而不从上下文中获取它而不会在 ef 核心中违反主键
- powershell - PowerShell:无法过滤通用列表的特殊情况
- c++ - 我的程序在执行期间找不到我的共享库
- sql - 选择主要电话号码(如果存在),否则使用 SQL 选择最新的电话号码一
- debian - 升级bulseye、sudo、su、login都不可用,如何修复?
- docker - 如何编写 DockerFile 将 Denodo 连接到 Airflow?
- sql - 使用 sql 从 Windows Scheduler 查询作业数据