Python의 채널 조건에 따라 이미지 픽셀 색상 바꾸기

Sep 12 2020

RGB 이미지가 있는데 같은 픽셀의 빨간색과 파란색 채널 값을 비교하여 픽셀 색상을 흰색 또는 검은 색으로 어떻게 변경할 수 있습니까?

if r_pixel > g_pixel:
    # make pixel white
else:
    # Make pixel black

내가 시도한 것은 다음과 같습니다.

img = cv2.imread("car.jpg")
b,g,r = cv2.split(img)
new = np.subtract(r , g)

출력은 순백색과 검정색 이미지 (0 또는 255)입니다.

답변

2 MarkSetchell Sep 11 2020 at 23:20

조건에 따라 각 픽셀 np.where()을 선택 255하거나 사용 합니다 0.

import cv2
import numpy as np

# Load image
img = cv2.imread('colorwheel.jpg')

# Wherever R>G, make result white, and black elsewhere
res = np.where(img[...,2]>img[...,1], 255, 0).astype(np.uint8)

# ALTERNATIVE SOLUTION FOLLOWS

# Or you could generate a Boolean (True/False) array and multiply by 255 to get the same result
res = ((img[...,2]>img[...,1]) * 255 ).astype(np.uint8)

입력

결과

1 GilPinsky Sep 11 2020 at 23:03

아래에 표시된대로 먼저 필요한 채널을 슬라이스 한 다음 두 채널을 비교하고 결과를 부울에서 uint8로 캐스트 한 다음 싱글 톤 채널을 압축하고 255를 곱할 수 있습니다.

r = img[:,:,2:]
g = img[:,:,1:2]
new = 255*np.squeeze(r>g,axis=2).astype('uint8')