Image processing and plotting
Usually, when using for loops and numpy together, you’re probably doing it wrong.

Some things you could replace in your code:


Use np.arange(256) instead of np.zeros + for i in range(256);
Use slicing instead of manually extracting values out of an array;
Use comparisons and .sum() instead of manually counting the number of pixels of a certain color intensity ((array_rgb == 42).sum(axis=1).sum(axis=0))


But all that is nothing compared to the use of numpy.histogram which does exactly what you want.



You also open the same image twice without closing it and yet, you use a with statement with your third open. Always use a with statement to better manage your resources.



I would use several plt.figure() and a single plt.show() to get all 5 plots show at once and be able to compare them. It will also make the whole thing more responsive.



Lastly, I would put all the code in a function that can be parametrized with the image name:

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt


def histogram(image_name):
    with Image.open(image_name) as image_file:
        array_grey = np.asarray(image_file.convert('L'))
        array_rgb = np.asarray(image_file.convert('RGB'))

    plt.figure()
    plt.imshow(array_grey, cmap='gray')
    plt.figure()
    plt.imshow(array_rgb)

    for i, color in enumerate('rgb'):
        hist, bins = np.histogram(array_rgb[..., i], bins=256, range=(0, 256))
        plt.figure()
        plt.bar(bins[:-1], hist, color=color)
    plt.show()


if __name__ == '__main__':
    histogram('picture1.jpg')


(Using the ... syntax from this answer)

Or you could keep the 3 different histograms in variables for further processing:

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt


def build_histograms(image_array):
    for i in range(image_array.shape[-1]):
        hist, _ = np.histogram(image_array[..., i], bins=256, range=(0, 256))
        yield hist


def histogram(image_name):
    with Image.open(image_name) as image_file:
        array_grey = np.asarray(image_file.convert('L'))
        array_rgb = np.asarray(image_file.convert('RGB'))

    plt.figure()
    plt.imshow(array_grey, cmap='gray')
    plt.figure()
    plt.imshow(array_rgb)

    red_frequencies, green_frequencies, blue_frequencies = build_histograms(array_rgb)
    grey_frequencies, = build_histograms(array_grey[..., np.newaxis])

    x_axis = np.arange(256)
    plt.figure()
    plt.bar(x_axis, red_frequencies, 1.0, color='r')
    plt.figure()
    plt.bar(x_axis, green_frequencies, 1.0, color='g')
    plt.figure()
    plt.bar(x_axis, blue_frequencies, 1.0, color='b')
    plt.figure()
    plt.bar(x_axis, grey_frequencies, 1.0, color='k')

    plt.show()


if __name__ == '__main__':
    histogram('picture1.jpg')