Extract image color (RGB)

Introduction

I had the opportunity to extract the colors (RGB) used from the image, so this is a memo.

environment

Language, package

Language, package version
Python 3.7.4
numpy 1.16.4
OpenCV 3.4.2

image

lena.jpg

Check the size of the image

Check the image you want to use.

import cv2
import numpy as np

bgr_array = cv2.imread('lena.jpg')
print(bgr_array.shape)
# (512, 512, 3)

When loading images using OpenCV, the colors are in the order ** BGR **. Therefore, the image is that three 512 x 512 ** B **, ** G **, ** R ** matrices are lined up.

Get GBR

For example, get the BGR value at the top left below.

print(bgr_array[0, 0, :])
# [128 138 225]

Image resizing

With the above method, it is necessary to acquire the BGR value 512 x 512 times. Create the following matrix for efficient operation.

\left[
    \begin{array}{rrr}
      b_{0} & g_{0} & r_{0} \\
      \vdots & \vdots &  \vdots \\
      b_{n} & g_{n} & r_{n}
    \end{array}
  \right]

Where n = 512 * 512-1. Then, we will extract unique values in the row direction.

reshaped_bgr_array = bgr_array.reshape(512*512, 3)

# axis=Specify row uniqueness with 0
unique_bgr_array = np.unique(reshaped_bgr_array, axis=0)

#List of unique bgr values
print(unique_bgr_array)
"""
[[ 29  14  76]
 [ 31  11  86]
 [ 31  27 146]
 ...
 [224 175 191]
 [224 180 197]
 [225 247 253]]
"""

#Number of unique bgr values
print(len(unique_bgr_array))
# 73852

#Percentage of unique bgr values to total pixels
print(len(unique_bgr_array)/(512*512))
# 0.2817230224609375

Functionalization

The above code depends on the size of the image, so make it a function so that it can be reused.

def extract_unique_color(img_path, rgb=False):
    bgr_array = cv2.imread(img_path)
    row, col, _ = bgr_array.shape
    reshaped_bgr_array = bgr_array.reshape(row * col, 3)
    unique_color_array = np.unique(reshaped_bgr_array, axis=0)

    if rgb:
        #Sort elements into rgb
        unique_color_array = unique_color_array[:, [2, 1, 0]]

    return unique_color_array

Finally

I introduced how to extract unique colors in images.

Recommended Posts

Extract image color (RGB)
Extract feature points of an image
Make an RGB 3 color composite diagram
100 image processing by Python Knock # 6 Color reduction processing
Image processing 100 knock Q.6. Color reduction processing explanation
Extract the color of the object in the image with Mask R-CNN and K-Means clustering