繁体   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