如何计算图像中的绿色百分比和蓝色百分比,已经制作了数组,用于循环读取图像文件

时间:2018-10-09 17:37:20

标签: python arrays image colors percentage

所以我已经能够读取文件并生成一个数组。我正在努力寻找方法来找到图像中绿色和蓝色的百分比。

#Import Libraries 

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
from PIL import Image
import glob

#option comd c and then cmd v to paste path /Users/Gilly/Desktop/Comp 180/images
#2 Reads the image of a sunset into an array LOOP

list_files=glob.glob("/Users/Gilly/Desktop/Comp 180/images/*.jpg")

for i in list_files:
    img = mpimg.imread(i)
    print(img)

#Plots the image from the array data 

for i in list_files:
    imgplot = plt.imshow(img)
    plt.show()

#Calculate % of Green and Blue in the images 

2 个答案:

答案 0 :(得分:0)

这是一个入门的提示。

要找到平均蓝色值,您必须遍历图像中的每个像素。您正在处理的图像(存储在img变量中)是一个行列表,每行是一个像素列表。

嵌套的for循环将使您遍历每个像素:

for row in img:
    for pixel in row:
        red = pixel[0]
        green = pixel[1]
        blue = pixel[2]
        print(blue)

如果遇到困难,请记住average = total / count

答案 1 :(得分:0)

emptyBlue = []
emptyGreen= []
for i in list_files:
    img = mpimg.imread(i)
    imgplot = plt.imshow(img)
    RGBtuple = np.array(img).mean(axis=(0,1))
    averageRed = RGBtuple[0]
    averageGreen = RGBtuple[1]
    averageBlue = RGBtuple[2]
    percentageGreen = averageGreen/(averageRed+averageGreen+averageBlue)
    percentageBlue = averageBlue/(averageRed+averageGreen+averageBlue)
    percentageRed = averageRed/(averageRed+averageGreen+averageBlue)
    emptyBlue+=[percentageBlue]
    emptyGreen+=[percentageGreen]
    print('Percent Blue',percentageBlue)
    print('Percent Green',percentageGreen)
print('Percentages of Blue',emptyBlue)
print('Percentages of Green',emptyGreen)
相关问题