最近写专利文书时遇到一个有趣的要求,论文中的彩色神经网络结构图要去掉所有的彩色,变成黑白的。

test.jpg
但是作为懒人,肯定是不想重画,因此写了一段Python代码来解决这个问题。主要思路就是过滤像素点,将亮度超过阈值的像素全部设为白色,对于亮度较低的像素则只进行灰度化,不进行额外处理。
import numpy as np
from PIL import Image
def adjust_brightness(image_path, threshold):
image = Image.open(image_path)
grayscale_image = image.convert("L")
pixel_array = np.array(grayscale_image)
# 按照阈值筛选像素点
bright_pixels = np.where(pixel_array > threshold)
dark_pixels=np.where(pixel_array <= threshold)
# 将高亮像素点设为白色(255)
pixel_array[bright_pixels] = 255
#pixel_array[dark_pixels] = 0 #考虑到jpg格式的压缩,彻底二值化的显示效果实测不是很好
result_image = Image.fromarray(pixel_array)
result_image.save("result_image.jpg")
return result_image
image_path = "test.jpg"
threshold = 180 #亮度阈值,可以灵活调整
result_image = adjust_brightness(image_path, threshold)
result_image.show()
最后的结果:

result_image.jpg
最后图片的效果还是很满意的,虽然有一点点糊,但这个主要是jpg等压缩格式导致的,反正对专利文书来说,肯定是够了。