Python extracts images based on specified color values

Cutting out an image based on a specified color value in Python

Cutting out an image based on a specified color value in Python

Cutting out an image is a common technique in image processing, used to extract a specific color or object from an image for subsequent processing or compositing. In this article, we will explain how to use Python to cut out an image based on a specified color value.

1. Preparation

Before performing the cutout operation, we need to prepare an image containing the color values of interest. We will use the OpenCV library in Python to accomplish this. If you haven’t installed the OpenCV library yet, you can install it using the following command:

pip install opencv-python

2. Loading an Image

First, we need to load an image and display it. In this example, we’ll use a multi-color image. Feel free to replace it with your own image as needed. Below is the code for reading and displaying an image:

import cv2
import matplotlib.pyplot as plt

# Read the image
img = cv2.imread('colorful_image.jpg')

# Convert the image from BGR format to RGB format
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# Displaying an Image
plt.imshow(img_rgb)
plt.axis('off')
plt.show()

In the above code, we first use OpenCV’s cv2.imread function to read an image named colorful_image.jpg. We then use the cv2.cvtColor function to convert the image from BGR to RGB format, and finally use the plt.imshow function to display the image.

3. Cutting Out the Image

Next, we will cut out the portion of the image containing the color specified by the user. Here’s the code to do this:

import numpy as np

# Define the color to be cut out (here we chose red)

target_color = np.array([255, 0, 0])

# Extract the target color
mask = np.all(img == target_color, axis=-1)

# Set the non-target color to black
result = np.zeros_like(img)
result[mask] = img[mask]

# Displaying the cutout image
plt.imshow(result)
plt.axis(‘off’)
plt.show()

In the above code, we first define the color to be cutout as red (RGB is [255, 0, 0]). We then use the np.all function to find the portions of the image containing the specified color value and generate the corresponding mask. Finally, we set the non-target color portions to completely black, ultimately displaying the cutout result.

Leave a Reply

Your email address will not be published. Required fields are marked *