最近寫專利文書時(shí)遇到一個(gè)有趣的要求,論文中的彩色神經(jīng)網(wǎng)絡(luò)結(jié)構(gòu)圖要去掉所有的彩色儒将,變成黑白的吏祸。
test.jpg
但是作為懶人,肯定是不想重畫钩蚊,因此寫了一段Python代碼來(lái)解決這個(gè)問題贡翘。主要思路就是過濾像素點(diǎn),將亮度超過閾值的像素全部設(shè)為白色砰逻,對(duì)于亮度較低的像素則只進(jìn)行灰度化鸣驱,不進(jìn)行額外處理。
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)
# 按照閾值篩選像素點(diǎn)
bright_pixels = np.where(pixel_array > threshold)
dark_pixels=np.where(pixel_array <= threshold)
# 將高亮像素點(diǎn)設(shè)為白色(255)
pixel_array[bright_pixels] = 255
#pixel_array[dark_pixels] = 0 #考慮到j(luò)pg格式的壓縮蝠咆,徹底二值化的顯示效果實(shí)測(cè)不是很好
result_image = Image.fromarray(pixel_array)
result_image.save("result_image.jpg")
return result_image
image_path = "test.jpg"
threshold = 180 #亮度閾值踊东,可以靈活調(diào)整
result_image = adjust_brightness(image_path, threshold)
result_image.show()
最后的結(jié)果:
result_image.jpg
最后圖片的效果還是很滿意的,雖然有一點(diǎn)點(diǎn)糊刚操,但這個(gè)主要是jpg等壓縮格式導(dǎo)致的闸翅,反正對(duì)專利文書來(lái)說(shuō),肯定是夠了菊霜。