How Can You Tell the Rgb Value of a Color From a Png?

How to calculate RGB values for some images in Python

A step-by-step guide.

A good exercise when studying Python is to summate RGB values for some images.
If you're request yourself: "what the hell do RGB mean?"; don't worry: this was the first question I've asked myself before coding for this exercise.
So, before the code, let'south talk near RGB.

Blackness and white, RGB, Blastoff level: some bones information

RGB stands for "Blood-red, Blue, Green"; it is a model of "condiment colors": their sum results in the white color. It is a model very used in electronic devices because it is helpful to visualize the pixels of an paradigm (and we are going to calculate even them).
This ways that when analyzing a colored image, Python — in some ways — gives u.s. three numbers: one for Red, one for Green, and the other for Blue.

Of grade, this means that from a blackness and white image we can calculate simply one value. On the contrary, the alpha level is a transparency, and this ways that we can calculate four values (ane for R, one for Yard, one for B, and one for the alpha level).

Preliminary report

All right, let'south utilise some code here!
Let'south say nosotros have a folder chosen images, and this is the directory:

          dst_img = "/home/Federico/images"        

In this folder nosotros have 3 images:

  • ane in blackness and white, named "bw.png"
  • i colored, named "daffodil.jpg"
  • one colored with the blastoff level, called "eclipse.png"

We want to calculate the RGB values for each one of these images. How can Python help usa?

Well, we can apply the library "PIL" which tin load images, and NumPy to transform the images in NumPy'southward arrays.

So, let's import the libraries:

          from PIL import Paradigm
import numpy as np
from tabulate import tabulate
import os

Now, earlier coding, we accept to understand some topics.

We'll use NumPy'south arrays and first of all, I want to think that the shape of an array tin be defined as the number of elements in each dimension; moreover, the "ndim" office returns the number of dimensions of an array.

Nosotros accept to use those concepts to empathize how to code properly before we really code.

So, allow's calculate the shape and the ndim for each array.

For the black and white image ("bw.png") we have:

          arr = np.array(Prototype.open(os.path.bring together(dst_img, "bw.png")))
print(arr.shape)
impress(arr.ndim)

and the result is:

          (512, 512)
ii

So, this prototype has the height and the width equal to 512 px; it besides has two dimensions, which is in accordance with the fact that is in black and white (information technology has merely ii dimensions).

For the RGB prototype ("daffodil.jpg") nosotros have:

          arr = np.array(Image.open(os.path.bring together(dst_img, "daffodil.jpg")))
impress(arr.shape)
print(arr.ndim)

and the upshot is:

          (500, 335, three)
3

this prototype has the height equal to 500 px and the width equal to 335 px; information technology too has 3 dimensions, which is in accordance with the fact that is an RGB paradigm.

In the end, for the RGB+alpha ("eclipse.png") prototype we take:

          arr = np.array(Image.open(os.path.bring together(dst_img, "eclipse.png")))
print(arr.shape)
impress(arr.ndim)

and the consequence is:

          (256, 256, 4)
3

this image has the height and the width equal to 256 px; it also has three dimensions, which is in accord with the fact that is an RGB paradigm, but it has 4 channels!

Using NumPy's "hateful" part, we can calculate the mean value for each color channel; now, we can create a loop to calculate our values.
Let' see the whole cod and then I'll explain some details.

The code

This is the lawmaking I've used to derive the data we've seen before from 3 images. Of class, this is just i manner to do it!

          from PIL import Image
import numpy as np
import bone
dst_img = "/dwelling house/Federico/images" #listing files in images folder
list_img = os.listdir(dst_img)
#iterating over dst_image to go the images as arrays
for image in sorted(list_img):
[file_name, ext] = os.path.splitext(paradigm) #splitting file name from its extension
arr = np.array(Image.open(os.path.join(dst_img, image))) #creating arrays for all the images
[h, due west] = np.shape(arr)[0:ii]#calculating height and width for each prototype
arr_dim = arr.ndim #calculating the dimension for each array
arr_shape = arr.shape #computing the shape for each array
if arr_dim == 2:
arr_mean = np.mean(arr)
impress(f'[{file_name}, greyscale={arr_mean:.1f}]')
else:
arr_mean = np.hateful(arr, axis=(0,1))
if len(arr_mean) == 3: #RGB CASE
impress(f'[{file_name}, R={arr_mean[0]:.1f}, M={arr_mean[ane]:.1f}, B={arr_mean[2]:.1f} ]')
else: #Blastoff Instance
print(f'[{file_name}, R={arr_mean[0]:.1f}, One thousand={arr_mean[1]:.1f}, B={arr_mean[2]:.1f}, Alpha={arr_mean[three]:.1f}]')

And this is the result:

          [bw, greyscale=21.5]
[daffodil, R=109.three, G=85.vi, B=5.0 ]
[eclipse, R=109.0, Chiliad=109.v, B=39.eight, Alpha=133.half-dozen]

Some code explanations

The importance of coding is to endeavour to generalize and so that we can employ the code again in the future if needed (with the due changes, of course).
In this example, I've decided to differentiate the images studying the "shape" and the "ndim" values derived from NumPy.

In the beginning, I wanted to derive the general information from all the images, and this is why I've imported them all using Numpy and the "PIL" library; I could, and so, calculate immediately the file name and the dimensions for each image, because this information tin exist calculated for each image, preliminary.

Then, I wanted to study the black and white epitome using the "if arr_dim == 2" statement: the black and white image, as I said before, has just two dimensions.
Then I wanted to study the RGB and the RGB with the Alpha channel images.
Then, before I wanted to generalize the calculation of the hateful values using the "arr_mean = np.hateful(arr, axis=(0,i))" code; in this example, I had to use "centrality=(0,1)" because those images take iii dimensions, and the calculation has to be done along the "x" and "y" axis in NumPy.

Then, I've differentiated the RGB from the RGB+ALPHA epitome with "len(arr_mean)"; since the RGB image has 3 channels, "len(arr_mean)" has to be equal to 3; instead, since the RGB+Blastoff has 4 channels, len(arr_mean) has to be equal to 4; hence, the underlined code before.

mathewoneven.blogspot.com

Source: https://medium.com/analytics-vidhya/how-to-calculate-rgb-values-for-some-images-in-python-ccf9abcea8f3

0 Response to "How Can You Tell the Rgb Value of a Color From a Png?"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel