[Python] Calculate the average value of the pixel value RGB of the object

1. Overview

This time, we will introduce the process of outputting the average pixel value RGB of the object to a csv file. apple_introduction.jpg

I want to find the average pixel value of an image of an object such as an apple! You can use it at that time. You can read about how this process was built in an article I posted to Qiita earlier. ↓ [[Python] Classify apples and pears from pixel values using a support vector machine (SVM)] [0] [0]:https://qiita.com/ZESSU/items/3083ce23e0405565765d This process is used to perform the pre-processing of the method described in this article, "Acquisition of the average value of the RGB pixel values of each apple and pear image".

The only information required for this process is an image showing the object. However, if the background is included, it cannot be calculated correctly, so use an app such as Paint to trim only the object neatly as shown in the figure below. apple_image.jpg

2. Environment

Since openCV is used for image processing and pandas is used as a data frame, please install these libraries in advance.

pip install opencv-python
pip install pandas

3. Code

The code is here. As a caveat, since openCV is used, the output will be in the order of BGR, not RGB.

bgr_csv.py


import cv2
import numpy as np
import pandas as pd

idir = 'input/'
odir = 'output/'
fname='apple'
num_photo=10
bgr = np.zeros((num_photo,3))

for k in range(num_photo):

    img = cv2.imread(idir + fname + '_' + str(k+1) + '.jpg')  #Start from number 1
    print(idir + fname + '_' + str(k+1) + '.jpg')
    h, w, c = img.shape #height, width, channnel

    #Initialize
    l=0
    b_ave=0; g_ave=0; r_ave=0

    for i in range(h):
        for j in range(w):
            #Pixel value[0,0,0](Black)を除外してピクセルの和とbgrのPixel valueの合計を計算する
            if(img[i,j,0] != 0 or img[i,j,1] != 0 or img[i,j,2] != 0 ):
                l+=1    #Calculate the number of pixels of interest
                #Calculate the sum of the pixel values of the target pixel
                b_ave=b_ave+img[i,j,0]
                g_ave=g_ave+img[i,j,1]
                r_ave=r_ave+img[i,j,2]

    #Obtain the average RGB pixel value by dividing the total pixel value by the number of pixels.
    b_ave=b_ave/l
    g_ave=g_ave/l
    r_ave=r_ave/l

    bgr[k]=np.array([b_ave, g_ave, r_ave])

df = pd.DataFrame(bgr, columns=['blue', 'green', 'red'])    #Match with opencv order quasi-BGR
df.to_csv(odir + fname + '.csv')

For example ...

fname='apple'
num_photo=1

In the case of, the average value of each pixel value of only one file of "input / apple_1.jpg " is output as "output / apple.csv".

4. Result

After processing the images of 10 apples, the apple.csv file with the average value of 10 BGR images will be output as shown below.

apple.csv


,blue,green,red
0,39.88469583593901,28.743374377331637,137.23369201906283
1,83.72563703792319,79.59471228615863,164.77884914463453
2,66.8231805177587,74.52501570023027,141.8854929872305
3,55.2837418388098,45.28968211495237,148.4160869099861
4,37.59397951454073,49.82323881039423,137.30237460066527
5,53.68868757437335,50.963264366051206,142.6121454070861
6,51.277953772145956,64.07145371348116,152.98116860260473
7,50.47702848900108,48.37151099891814,124.46714749368914
8,40.35442093843233,52.0682126390019,137.8299091402224
9,48.18758094199441,55.87655919841865,145.6361529548088

As described in the overview, using the apple and pear csv file output by this code ↓ [[Python] Classify apples and pears from pixel values using a support vector machine (SVM)] [1] [1]:https://qiita.com/ZESSU/items/3083ce23e0405565765d I am doing. Please take a look at this article as well!

Recommended Posts

[Python] Calculate the average value of the pixel value RGB of the object
Tips: [Python] Calculate the average value of the specified area with bedgraph
[Python3] Rewrite the code object of the function
Calculate the total number of combinations with python
Find the divisor of the value entered in python
the zen of Python
Calculate the regression coefficient of simple regression analysis with python
Towards the retirement of Python2
About the ease of Python
Calculate the number of changes
About the features of Python
The Power of Pandas: Python
[Python] Change the Cache-Control of the object uploaded to Cloud Storage
Inherit the standard library to find the average value of Queue
Calculate the square root of 2 in millions of digits with python
[Python] Calculate the angle consisting of three points on the coordinates
Pixel manipulation of images in Python
Find the definition of the value of errno
The story of Python and the story of NaN
I compared the calculation time of the moving average written in Python
[Python] Find the second smallest value.
[Python] The stumbling block of import
First Python 3 ~ The beginning of repetition ~
How to know the internal structure of an object in Python
[Cloudian # 9] Try to display the metadata of the object in Python (boto3)
Calculate the editing distance as an index of pronunciation similarity [python]
Existence from the viewpoint of Python
pyenv-change the python version of virtualenv
About the return value of pthread_mutex_init ()
Get the attributes of an object
Change the Python version of Homebrew
About the return value of the histogram.
[Python] Understanding the potential_field_planning of Python Robotics
Review of the basics of Python (FizzBuzz)
Touch the object of the neural network
Get and set the value of the dropdown menu using Python and Selenium
Calculate the previous month in Python
The meaning of ".object" in Django
About the basics list of Python basics
Learn the basics of Python ① Beginners
[Python] Yuriko Koike Calculate the number of votes you need exactly [matplotlib]
Calculate the shortest route of a graph with Dijkstra's algorithm and Python
Python Note: When you want to know the attributes of an object
[Python] Calculate the number of digits required when filling in 0s [Note]
Calculate the probability of being a squid coin with Bayes' theorem [python]
About Python code for simple moving average assuming the use of Numba
Get the return value of an external shell script (ls) with python3
Find the maximum value python (fixed ver)
Change the length of Python csv strings
Check the behavior of destructor in Python
[Python3] Understand the basics of Beautiful Soup
The story of making Python an exe
Learning notes from the beginning of Python 1
Check the existence of the file with python
About the virtual environment of python version 3.7
Let Python calculate Euler-Lagrange's equation of motion
[Python] Understand the content of error messages
I didn't know the basics of Python
The result of installing python in Anaconda
[Python] Try pydash of the Python version of lodash
[python] Checking the memory consumption of variables