有這樣的畫面

我用一個網站檢測了背景的rgb,它是42、44、54。旨在用那個 rgb 將像素替換為白色 這是我的嘗試,但我沒有得到預期的輸出
import cv2
import numpy as np
# Load image
im = cv2.imread('Sample.png')
# Make all perfectly green pixels white
im[np.all(im == (42,44,54), axis=-1)] = (255, 255, 255)
# Save result
cv2.imwrite('Output.png',im)
我再次搜索并找到以下代碼(有點作業)
from PIL import Image
img = Image.open("Sample.png")
img = img.convert("RGB")
datas = img.getdata()
new_image_data = []
for item in datas:
# change all white (also shades of whites) pixels to yellow
if item[0] in list(range(42, 44)):
new_image_data.append((255, 255, 255))
else:
new_image_data.append(item)
# update image data
img.putdata(new_image_data)
# save new image
img.save("Output.png")
# show image in preview
img.show()
我還需要將除白色像素外的任何其他 rgb 更改為黑色。只需在去除背景顏色后將所有彩色字符變為黑色
我仍在嘗試(等待專家貢獻并提供更好的解決方案)。以下是相當不錯但到目前為止還不是那么完美
from PIL import Image
import numpy as np
img = Image.open("Sample.png")
width = img.size[0]
height = img.size[1]
for i in range(0,width):
for j in range(0,height):
data = img.getpixel((i,j))
if (data[0]>=36 and data[0]<=45) and (data[1]>=38 and data[1]<=45) and (data[2]>=46 and data[2]<=58):
img.putpixel((i,j),(255, 255, 255))
if (data[0]==187 and data[1]==187 and data[2]==191):
img.putpixel((i,j),(255, 255, 255))
img.save("Output.png")
我想過使用 Pillow 將影像轉換為灰度
from PIL import Image
img = Image.open('Sample.png').convert('LA')
img.save('Grayscale.png')
影像被清除但如何在這種模式下替換 rgb 像素?我嘗試了相同的先前代碼并更改了 rgb 值但沒有作業并且由于模式為 L 存在錯誤
uj5u.com熱心網友回復:
您可以一次性完成這兩個步驟:
from PIL import Image
def is_background(item, bg):
# Tweak the ranges if the result is still unsatisfying
return (item[0] in range(bg[0] - 20, bg[0] 20)) or \
(item[1] in range(bg[1] - 20, bg[1] 20)) or \
(item[2] in range(bg[2] - 20, bg[2] 20))
img = Image.open("Sample.png")
img = img.convert("RGB")
datas = img.getdata()
bg = [42, 44, 54] # Background RGB color
new_image_data = []
for item in datas:
# change all background to white and keep all white
if is_background(item, bg) or item == (255, 255, 255):
new_image_data.append((255, 255, 255))
else:
# change non-background and non-white to black
new_image_data.append((0, 0, 0))
img.putdata(new_image_data)
img.save("Output.png")
img.show()
這是結果。
注意:
我們需要
is_background,因為背景不是完全相同的顏色,有非常輕微的變化這種檢測背景的方法非常基本,還有更復雜的方法。
uj5u.com熱心網友回復:
問題是 OpenCV 遵循 BGR 格式,而您的像素值為 RGB。修復如下。
# Make all perfectly green pixels white
im[np.all(im == (54,44,42), axis=-1)] = (255, 255, 255)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/439810.html
上一篇:ValueError:所有輸入陣列必須具有相同數量的dims,但索引0處的arr有1個維度,索引11處的arr有2個維度
