Opencv python extract channel

Получение красного, зеленого и синего канала из цветного изображения в Python

Чтобы извлечь красный канал изображения, мы сначала прочитаем цветное изображение с помощью cv2, а затем извлечем 2D-массив.

В этом руководстве Python мы узнаем, как извлечь красный канал из цветного изображения, применив нарезку массива к представлению массива numpy изображения.

Пошаговый процесс извлечения

  1. Прочтите изображение с помощью cv2.imread().
  2. imread() возвращает массив BGR (Blue-Green-Red), это трехмерный массив, т.е. массивы 2D пикселей для трех цветовых каналов.
  3. Извлеките только красный канал, разрезав массив.

Пример 1

В следующем примере мы реализуем все шаги, упомянутые выше, чтобы извлечь красный канал из следующего изображения.

Как извлечь красный канал из изображения?

import cv2 #read image src = cv2.imread('D:/cv2-resize-image-original.png', cv2.IMREAD_UNCHANGED) print(src.shape) #extract red channel red_channel = src[. 2] #write red channel to greyscale image cv2.imwrite('D:/cv2-red-channel.png',red_channel)

Мы добавили к изображению красный канал. Поскольку это всего лишь 2D-массив со значениями от 0 до 255, выходные данные выглядят как изображение в оттенках серого, но это значения красного канала.

Выходные данные, как изображение в оттенках серого

Если вы посмотрите на треугольники, более зеленый и синий будут темнее другого.

Чтобы визуализировать изображение в красном цвете, сведем к нулям синюю и зеленую составляющие.

import cv2 import numpy as np #read image src = cv2.imread('D:/cv2-resize-image-original.png', cv2.IMREAD_UNCHANGED) print(src.shape) # extract red channel red_channel = src[. 2] # create empty image with same shape as that of src image red_img = np.zeros(src.shape) #assign the red channel of src to empty image red_img[. 2] = red_channel #save image cv2.imwrite('D:/cv2-red-channel.png',red_img)

Визуализация изображения в красном цвете

В этом уроке на примерах Python мы узнали, как выделить красный канал цветного изображения.

Как получить зеленый канал?

Чтобы извлечь зеленый канал изображения, сначала прочитайте цветное изображение с помощью библиотеки OpenCV в Python, а затем извлеките 2D-массив зеленого канала из массива изображений, используя нарезку изображения.

В этом уроке мы научимся извлекать зеленый канал с помощью примеров программ.

Пошаговый процесс извлечения

  1. Прочтите изображение с помощью cv2.imread().
  2. imread() возвращает массив BGR (Blue-Green-Red), это трехмерный массив, т.е. массивы 2D пикселей для трех цветовых каналов.
  3. Извлеките только зеленый канал, разрезав массив.
Читайте также:  Qt creator python как пользоваться

Пример 1

В следующем примере мы реализуем все шаги, упомянутые выше, чтобы извлечь Зеленый канал из следующего изображения.

Как извлечь Зеленый канал из изображения?

import cv2 #read image src = cv2.imread('D:/cv2-resize-image-original.png', cv2.IMREAD_UNCHANGED) print(src.shape) #extract green channel green_channel = src[. 1] #write green channel to greyscale image cv2.imwrite('D:/cv2-green-channel.png',green_channel)

Мы добавили зеленый канал к изображению. Поскольку это всего лишь 2D-массив со значениями от 0 до 255, выходные данные выглядят как изображение в оттенках серого, но это значения зеленого канала.

Выходные данные, как изображение в оттенках серого OpenCV

Если вы посмотрите на треугольники, красный и синий темнее другого.

Чтобы визуализировать изображение в зеленом цвете, сделаем красную и синюю составляющими нулями.

import cv2 import numpy as np #read image src = cv2.imread('D:/cv2-resize-image-original.png', cv2.IMREAD_UNCHANGED) print(src.shape) # extract green channel green_channel = src[. 1] # create empty image with same shape as that of src image green_img = np.zeros(src.shape) #assign the green channel of src to empty image green_img[. 1] = green_channel #save image cv2.imwrite('D:/cv2-green-channel.png',green_img)

Визуализация изображения в зеленом цвете

Мы узнали, как извлечь зеленый канал из изображения.

Как получить синий канал?

Чтобы извлечь синий канал изображения в Python, сначала прочтите цветное изображение с помощью библиотеки OpenCV, а затем извлеките 2D-массив синего канала из массива изображений, используя нарезку изображения.

Пошаговый процесс извлечения

  1. Прочтите изображение с помощью cv2.imread().
  2. imread() возвращает массив BGR (Blue-Green-Red), это трехмерный массив, т.е. массивы 2D пикселей для трех цветовых каналов.
  3. Извлеките только синий канал, обратившись к массиву.

Пример 1

В следующем примере мы реализуем последовательность шагов, упомянутых выше, чтобы извлечь синий канал из следующего изображения.

Извлечение синего канала из изображения

import cv2 #read image src = cv2.imread('D:/cv2-resize-image-original.png', cv2.IMREAD_UNCHANGED) print(src.shape) #extract blue channel blue_channel = src[. 0] #write blue channel to greyscale image cv2.imwrite('D:/cv2-blue-channel.png',blue_channel)

Мы добавили синий канал к изображению. Поскольку это всего лишь 2D-массив со значениями от 0 до 255, выходные данные выглядят как изображение в оттенках серого, но это значения синего канала.

Выходное изображение (синий канал) в OpenCV

Если вы посмотрите на треугольники, красный и зеленый темнее другого.

Чтобы визуализировать изображение в синем цвете, сведем к нулю красную и зеленую составляющие.

import cv2 import numpy as np #read image src = cv2.imread('D:/cv2-resize-image-original.png', cv2.IMREAD_UNCHANGED) print(src.shape) # extract blue channel blue_channel = src[. 0] # create empty image with same shape as that of src image blue_img = np.zeros(src.shape) #assign the red channel of src to empty image blue_img[. 0] = blue_channel #save image cv2.imwrite('D:/cv2-blue-channel.png',blue_img)

Визуализация изображения в синем цвете

В этом уроке на примерах Python мы узнали, как извлечь синий канал из изображения.

Источник

Python Extract Red Channel from Color Image

To extract red channel of image, we will first read the color image using cv2 and then extract the red channel 2D array from the image array.

In this tutorial, we shall learn how to extract the red channel from the colored image, by applying array slicing on the numpy array representation of the image.

Читайте также:  Importing modules in java

Step by step process to extract Red Channel of Color Image

Following is the sequence of steps to extract red channel from an image.

  1. Read image using cv2.imread().
  2. imread() returns BGR (Blue-Green-Red) array. It is three dimensional array i.e., 2D pixel arrays for three color channels.
  3. Extract the red channel alone by slicing the array.

Examples

1. Get red color channel from given image

In the following example, we will implement all the steps mentioned above to extract the Red Channel from the following image.

Input Image

Python Extract Red Channel from Color Image

Python Program

import cv2 #read image src = cv2.imread('D:/cv2-resize-image-original.png', cv2.IMREAD_UNCHANGED) print(src.shape) #extract red channel red_channel = src[. 2] #write red channel to greyscale image cv2.imwrite('D:/cv2-red-channel.png',red_channel) 

We have written the red channel to an image. As this is just a 2D array with values ranging from 0 to 255, the output looks like a greyscale image, but these are red channel values.

Output Image

Python OpenCV - Extract Red Channel from Image

If you observe the triangles, the greener and bluer ones are more darker than the other.

To visualize the image in red color, let us make the blue and green components to zeroes.

Python Program

import cv2 import numpy as np #read image src = cv2.imread('D:/cv2-resize-image-original.png', cv2.IMREAD_UNCHANGED) print(src.shape) # extract red channel red_channel = src[. 2] # create empty image with same shape as that of src image red_img = np.zeros(src.shape) #assign the red channel of src to empty image red_img[. 2] = red_channel #save image cv2.imwrite('D:/cv2-red-channel.png',red_img) 

Output Image

Python OpenCV - Extract Red Channel from Image

Summary

In this Python OpenCV Tutorial, we learned how to extract red channel of a colored image.

Источник

Python Extract Green Channel from Color Image

To extract green channel of image, first read the color image using Python OpenCV library and then extract the green channel 2D array from the image array using image slicing.

In this tutorial, we shall learn how to extract the green channel, with the help of example programs.

Step by step process to extract Green Channel of Color Image

Following is a step by step process to extract green channel from image.

  1. Read image using cv2.imread().
  2. imread() returns BGR (Blue-Green-Red) array. It is three dimensional array i.e., 2D pixel arrays for three color channels.
  3. Extract the green channel alone by slicing the array.

Examples

1. Get green color channel from given image

In the following example, we shall implement all the steps mentioned above to extract the Green Channel from the following image.

Source Image or Input Image

Python Extract Green Channel from Color Image

Python Program

import cv2 #read image src = cv2.imread('D:/cv2-resize-image-original.png', cv2.IMREAD_UNCHANGED) print(src.shape) #extract green channel green_channel = src[. 1] #write green channel to greyscale image cv2.imwrite('D:/cv2-green-channel.png',green_channel) 

We have written the green channel to an image. As this is just a 2D array with values ranging from 0 to 255, the output looks like a greyscale image, but these are green channel values.

Читайте также:  Html код все команды

Output Image

Python OpenCV - Extract Green Channel from Image

If you observe the triangles, the red and blue ones are more darker than the other.

To visualize the image in green color, let us make the red and blue components to zeroes.

Python Program

import cv2 import numpy as np #read image src = cv2.imread('D:/cv2-resize-image-original.png', cv2.IMREAD_UNCHANGED) print(src.shape) # extract green channel green_channel = src[. 1] # create empty image with same shape as that of src image green_img = np.zeros(src.shape) #assign the green channel of src to empty image green_img[. 1] = green_channel #save image cv2.imwrite('D:/cv2-green-channel.png',green_img) 

Output Image

Python OpenCV - Extract Green Channel from Image

Summary

In this Python OpenCV Tutorial, we learned how to extract green channel from an image.

Источник

Python Extract Blue Channel from Color Image

To extract blue channel of image, first read the color image using Python OpenCV library and then extract the blue channel 2D array from the image array using image slicing.

Step by step process to extract Blue Channel of Color Image

Following is sequence of steps to get the blue channel of colored image.

  1. Read image using cv2.imread().
  2. imread() returns BGR (Blue-Green-Red) array. It is three dimensional array i.e., 2D pixel arrays for three color channels.
  3. Extract the blue channel alone by accessing the array.

Examples

1. Get blue color channel from image

In the following example, we shall implement the sequence of steps mentioned above, to extract the Blue Channel from the following image.

Source Image or Input Image

Python Extract Blue Channel from Color Image

Python Program

import cv2 #read image src = cv2.imread('D:/cv2-resize-image-original.png', cv2.IMREAD_UNCHANGED) print(src.shape) #extract blue channel blue_channel = src[. 0] #write blue channel to greyscale image cv2.imwrite('D:/cv2-blue-channel.png',blue_channel) 

We have written the blue channel to an image. As this is just a 2D array with values ranging from 0 to 255, the output looks like a greyscale image, but these are blue channel values.

Output Image (Blue Channel)

Python OpenCV - Extract Blue Channel from Image

If you observe the triangles, the red and green ones are more darker than the other.

To visualize the image in blue color, let us make the red and green components to zeroes.

Python Program

import cv2 import numpy as np #read image src = cv2.imread('D:/cv2-resize-image-original.png', cv2.IMREAD_UNCHANGED) print(src.shape) # extract blue channel blue_channel = src[. 0] # create empty image with same shape as that of src image blue_img = np.zeros(src.shape) #assign the red channel of src to empty image blue_img[. 0] = blue_channel #save image cv2.imwrite('D:/cv2-blue-channel.png',blue_img) 

Output Image

Python OpenCV - Extract Blue Channel from Image

Summary

In this Python OpenCV Tutorial, we learned how to extract blue channel from an image.

Источник

Оцените статью