图像有三个通道(R、G、B)。在
图像中所有的白色块都是白色的,因为它们在三个通道中都有255个像素。在
为了将白块转换成红色,我们首先使用cv2读取图像矩阵,然后将通道1(“G”)和通道2(“B”)中值为255的所有像素更改为0。所以,现在我们只有0频道(“R”)中的像素值为255。这样,图像的所有白色块都变为红色块。在
附两份文件:1。旧的_方块字.jpg2新的_方块字.jpg在
旧的_方块字.jpg有白色方块,颜色为红色,新显示_方块字.jpg. 在
检查以下脚本:# libraries
import cv2
import numpy as np
import Image
# name of jpg image file
jpg_image_name = "old_square.jpg"
# reading jpg image and getting its matrix
jpg_image = cv2.imread(jpg_image_name)
jpg_image_mat = np.array(jpg_image)
# getting image features
pixel_value_to_replace = 255
rows, cols, channels = jpg_image_mat.shape
"""##########################################
An image have three channels (R, G, B). So,
putting 0 in other two channels to make image
red at white squares.
##########################################"""
# changing 255 to 0 in first channel
for i in range(rows):
for j in range(cols):
if(jpg_image_mat[i, j, 1] == pixel_value_to_replace):
jpg_image_mat[i, j, 1] = 0
# changing 255 to 0 in second channel
for i in range(rows):
for j in range(cols):
if(jpg_image_mat[i, j, 2] == pixel_value_to_replace):
jpg_image_mat[i, j, 2] = 0
# saving new modified matrix in image format
new_image = Image.fromarray(jpg_image_mat)
new_image.save("new_square.jpg")