我有這張圖片:

我想用紅色像素改變與黑色像素接觸的白色像素組。可以使用以下代碼將特定顏色替換為另一種顏色:
import numpy as np
from PIL import Image
im = Image.open('fig1.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)
是否可以將白色像素樣本替換為紅色像素,而只是將白色像素與黑色像素接觸?
uj5u.com熱心網友回復:
更新的答案
我仍然不能 100% 確定你想要什么,但這應該為你做你想做的事提供一個很好的基礎:
#!/usr/bin/env python3
from PIL import Image
import numpy as np
from skimage.morphology import dilation
# Load image - and make into Numpy array
# It is a palette image. 0=black, 1=white, 2=red
im = Image.open('start.png')
na = np.array(im)
# Make mask of white pixels - True where white
whiteMask = na==1
Image.fromarray((whiteMask*255).astype(np.uint8)).save('DEBUG-whiteMask.png')
# Make mask of black pixels - True where black
blackMask = na==0
Image.fromarray((blackMask*255).astype(np.uint8)).save('DEBUG-blackMask.png')
# Footprint of structuring element for morphology
# Unused at the moment:
# footprint = np.zeros((3, 3), dtype=np.uint8)
# footprint[1, 1] = 1
# Do the morphology on blackMask
touchingBlack = dilation(blackMask, footprint=None)
# Now find pixels that are both white and touching black
resultMask = np.logical_and(whiteMask, touchingBlack)
Image.fromarray((resultMask*255).astype(np.uint8)).save('DEBUG-resultMask.png')
# Make those pixels red
na[resultMask] = 2
# Convert back into PIL Image and reinstate original palette
res = Image.fromarray(na)
res.putpalette(im.getpalette())
res.save('result.png')
它從下面使用我的“已校正”起始影像,并生成:

原始答案
如果/當您提供體面的無損 PNG 輸入影像并闡明您所說的“像素接觸黑色”的含義時,我將更新此答案。
目前,我已將您的影像“校正”為三種顏色:

并在終端中使用ImageMagick嘗試我的演算法以方便起見,直到我們確定目標是什么。
# Find white pixels
magick start.png -fill black opaque white white.png

# Find black pixels
magick start.png -fill white opaque black -negate black.png

# Find pixels touching black pixels
magick black.png -morphology dilate square:1 black-d.png

# Find black pixels that are both white and touching black
magick white.png black-d.png -compose darken -composite result.png

I "corrected" the original image, which was a lossy JPEG into a 3-colour PNG as follows...
First, I made a swatch of the 3 pure colours I wanted to remap the image to. I did that with ImageMagick as follows:
magick xc:red xc:black xc:white append swatch.png
That makes a tiny 3x1 image with 1 red, 1 black and 1 white pixel. Then I remapped the original image to those 3 colours with ImageMagick using:
magick original.jpg dither -remap swatch.png start.png
Then I hand-edited 6-8 stray pixels.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/446932.html
下一篇:如何將段落放置在影像塊的右側?
