簡體   English   中英

在兩個不同的 colors 之間更改像素 colors

[英]Change pixel colors between two different colors

我有這張圖片:

在此處輸入圖像描述

我想改變紅色和黃色像素之間或與之接觸的像素組(綠色),通過紅色,這樣:

在此處輸入圖像描述

抱歉,我沒有任何代碼,因為我不知道如何開始,也沒有找到執行此操作的方法。 我認為與PIL相關的類似邏輯,如下所示:

import numpy as np
from PIL import Image

im = Image.open('image.png')
data = np.array(im)

r1, g1, b1 = 255, 255, 255 # Original value
r2, g2, b2 = 0, 0, 0 # Value that we want to replace it with

red, green, blue = data[:,:,0], data[:,:,1], data[:,:,2]
mask = (red == r1) & (green == g1) & (blue == b1)
data[:,:,:3][mask] = [r2, g2, b2]

im = Image.fromarray(data)

但是有條件的。

我們可以使用cv2.floodFill方法開始求解。

主要階段:

  • 使用floodFill用黑色填充下部(假設只有黃色和綠色像素)。
  • 使用floodFill用黑色填充頂部(假設只有紅色和綠色像素)。
  • 查找頂部和底部均為零(黑色)的像素。
  • 用紅色替換都是黑色的像素。

代碼示例:

import cv2
import numpy as np

img = cv2.imread('red_yellow_green.jpg')

cols, rows = img.shape[0], img.shape[1]

red = img[0, 0, :].tolist() # Get the red color from the top left corner

# Make the green a "true green"
img2 = img.copy()
green_ch = img2[:, :, 1]
green_ch[green_ch > 100] = 255

# Fill the lower part with black (assume only yellow and green pixels)
bot_black = img2
cv2.floodFill(bot_black, None, seedPoint=(rows-1, cols-1), newVal=(0, 0, 0), loDiff=(255, 20, 255), upDiff=(255, 20, 255))

# Fill the top part with black (assume only red and green pixels)
top_black = img.copy()
cv2.floodFill(top_black, None, seedPoint=(0, 0), newVal=(0, 0, 0), loDiff=(50, 255, 50), upDiff=(50, 255, 50))

# Find pixels where both top and bottom are zeros
both_black = np.logical_and(np.all(bot_black[:, :, 0:3] == (0, 0, 0), 2), np.all(top_black[:, :, 0:3] == (0, 0, 0), 2))

# Convert to uint8 and dilate (this part is just for aesthetics).
both_black = both_black.astype(np.uint8)*255
both_black = cv2.dilate(both_black, np.ones((5,5)))

# Replace the pixels that are both black with red color
img[both_black == 255] = red

# Show images for testing:
cv2.imshow('bot_black', bot_black)
cv2.imshow('top_black', top_black)
cv2.imshow('both_black', both_black)
cv2.imshow('img', img)
cv2.waitKey()
cv2.destroyAllWindows()

結果:

bot_black
在此處輸入圖像描述

top_black
在此處輸入圖像描述

both_black :
在此處輸入圖像描述

img
在此處輸入圖像描述


上述解決方案不是最通用的解決方案。
還有一個選項可以找到所有綠色輪廓,創建輪廓周長的掩碼,並分析每個輪廓周長的 colors(並用紅色填充混合周長 colors 的輪廓)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM