将 RGB 转换为黑白

convert RGB to black and white

Python 中的代码片段应将 rgb 图像转换为黑白图像,但仅输出黑色图像。不知道哪里出了问题(输入输出图片应该是bmp)

from PIL import Image
import numpy as np

raw_img = Image.open(r"image adress")
img = raw_img.load()
x,y = raw_img.size
threshold = 300
bw_img = [[0]*y]*x # blank image

for i in range(x):
  for j in range(y):
    if img[i,j] < threshold:
      bw_img[i][j] = 0
    else:
      bw_img[i][j] = 1


Image.fromarray(np.asarray(bw_img),mode="P").save("your_nwe_image.bmp")

您需要更换

threshold = 300

threshold = 128

因为 Image.open 总是 returns 8 位图像,其中 255 是最大值。

下面是我将如何做这个(不使用 OpenCV 模块):

from PIL import Image
import numpy as np

def not_black(color):
    return (color * [0.2126, 0.7152, 0.0722]).sum(-1) < 128

raw_img = Image.open(r"image adress")
img = np.array(raw_img)

whites = not_black(img)
img[whites] = 255
img[~whites] = 0

Image.fromarray(img).save("your_nwe_image.bmp")

然而,使用 OpenCV,它简化为:

import cv2

img = cv2.imread(r"biss3.png", 0)
_, thresh = cv2.threshold(img, 128, 255, cv2.THRESH_BINARY)

cv2.imwrite("your_nwe_image.bmp", thresh)