0
我想填充以下圖像的每個單元格中的顏色。我已經使用for循環來逐個像素地填充這些框。當使用填充邊框也會變成彩色,這是主要問題。如何使用openCV和Python在每個矩形塊中填充顏色?
這些是單元格的尺寸。
Width:20px;
身高:20px;
邊框寬度:20px;
當相鄰單元格連接時,它們的邊框寬度將爲4 px。
所以我不想彩色邊框細胞(白色部分)的唯一地區應和着色。
我想填充以下圖像的每個單元格中的顏色。我已經使用for循環來逐個像素地填充這些框。當使用填充邊框也會變成彩色,這是主要問題。如何使用openCV和Python在每個矩形塊中填充顏色?
這些是單元格的尺寸。
Width:20px;
身高:20px;
邊框寬度:20px;
當相鄰單元格連接時,它們的邊框寬度將爲4 px。
所以我不想彩色邊框細胞(白色部分)的唯一地區應和着色。
圖像有三個通道(R,G,B)。
圖像中的所有白色塊都是白色的,因爲它們全部三個通道的像素都是255像素。
要將白色塊轉換爲紅色,首先我們通過使用cv2讀取圖像矩陣,然後將通道1(「G」)和通道2(「B」)中具有值255的所有像素更改爲0因此,現在我們只有通道0(「R」)的像素值爲255。這樣,所有圖像的白色塊都變爲紅色塊。
兩個文件附:1. old_square.jpg 2. new_square.jpg
old_square.jpg具有被着色爲紅色,在new_square.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")
謝謝您的回答@sansingh但我不想邊框和白色區域的變化顏色只能用不同的顏色,而不是着色黑色。 –
我可以將您發佈的圖片視爲您必須使用的圖片嗎? – sansingh
@ Dash_25你可以使用相同的邏輯,就像我在上面的腳本中給出的結果一樣。 – sansingh