簡體   English   中英

用白色替換特定像素

[英]Replace specific pixels by rgb with white color

有這樣的畫面在此處輸入圖像描述

我用一個網站檢測了背景的rgb,它是42、44、54。 旨在用那個 rgb 將像素替換為白色這是我的嘗試,但我沒有得到預期的 output

 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 存在錯誤

您可以在一個 go 中完成這兩個步驟:

 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因為背景不是完全相同的顏色,有非常輕微的變化

  • 這種檢測背景的方法非常基本,還有更復雜的方法。

問題是 OpenCV 遵循 BGR 格式,您的像素值為 RGB。 修復如下。

 # Make all perfectly green pixels white im[np.all(im == (54,44,42), axis=-1)] = (255, 255, 255)

暫無
暫無

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

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