在Python中计算红色像素值并绘制直方图

时间:2017-05-22 14:15:58

标签: python opencv numpy image-processing scikit-image

我有一组图像,它们位于3个单独的文件夹中,基于它们的类型。我想迭代每个Type并计算每个图像的红色像素值。我设置了红色的限制,范围从200到256.我想为每种类型创建直方图,然后聚类直方图并区分3个类。我对Python的经验非常有限,我坚持如何隔离和计算红色像素值。我已将我的代码和结果直方图附加到类型1,这是一条直线。有人可以帮忙吗?

import numpy as np
import cv2
import os.path
import glob
import matplotlib.pyplot as plt

## take the image, compute sum of all row colors and return the percentage
#iterate through every Type
for t in [1]:

    #load_files
    files = glob.glob(os.path.join("..", "data", "train", "Type_{}".format(t), "*.jpg"))
    no_files = len(files)

    #iterate and read
    for n, file in enumerate(files):
        try:
            image = cv2.imread(file)
            hist = cv2.calcHist([img], [0], None, [56], [200, 256])

            print(file, t, "-files left", no_files - n)

        except Exception as e:
            print(e)
            print(file)

plt.plot(hist)
plt.show()

1 个答案:

答案 0 :(得分:2)

这是我提出的解决方案。我已经冒昧地重构和简化你的代码了。

import os
import glob
import numpy as np
import matplotlib.pyplot as plt
from skimage import io

root = 'C:\Users\you\imgs'  # Change this appropriately
folders = ['Type_1', 'Type_2', 'Type_3']
extension = '*.bmp'  # Change if necessary
threshold = 150  # Adjust to fit your neeeds

n_bins = 5  # Tune these values to customize the plot
width = 2.
colors = ['cyan', 'magenta', 'yellow']
edges = np.linspace(0, 100, n_bins+1)
centers = .5*(edges[:-1]+ edges[1:])

# This is just a convenience class used to encapsulate data
class img_type(object):
    def __init__(self, folder, color):
        self.folder = folder
        self.percents = []
        self.color = color

lst = [img_type(f, c) for f, c in zip(folders, colors)]

fig, ax = plt.subplots()

for n, obj in enumerate(lst):
    filenames = glob.glob(os.path.join(root, obj.folder, extension))

    for fn in filenames:
        img = io.imread(fn)
        red = img[:, :, 0]
        obj.percents.append(100.*np.sum(red >= threshold)/red.size)

    h, _ = np.histogram(obj.percents, bins=edges)
    h = np.float64(h)
    h /= h.sum()
    h *= 100.
    ax.bar(centers + (n - .5*len(lst))*width, h, width, color=obj.color)

ax.legend(folders)
ax.set_xlabel('% of pixels whose red component is >= threshold')
ax.set_ylabel('% of images')
plt.show()

multiple bar plot

请注意,我使用scikit-image而不是OpenCV来读取图像。如果这不适合您,请插入import cv2并更改:

    img = io.imread(fn)
    red = img[:, :, 0]

为:

    img = cv2.imread(fn)
    red = img[:, :, 2]