Image_Binarization/binarization.py
2025-05-14 16:47:42 +08:00

50 lines
1.3 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import cv2
from PIL import Image
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['simHei']
plt.rcParams['axes.unicode_minus'] = False
from rembg import remove # 程序首次运行需要用到onnxruntime库来下载模型实测国内下载速度100kb/s文件176Mb本人推荐使用魔法上网。
# 对图像主题进行抠图处理
if __name__=='__main__':
# 待处理的图片路径
input_path = 'file/zmn.jpg'
# 处理后存储的图片路径
output_path = 'buckle/zmn.png'
with open(input_path, 'rb') as i:
with open(output_path, 'wb') as o:
input = i.read()
output = remove(input)
o.write(output)
# 读取抠图后照片
image = cv2.imread("buckle/zmn.png", cv2.IMREAD_GRAYSCALE)
# 对图像进行二值化处理
_, binary_image = cv2.threshold(image, 1, 255, cv2.THRESH_BINARY)
# 保存结果照片
cv2.imwrite("result/result_zmn.png", binary_image)
# 展示图像
plt.subplot(1,3,1)
image_zmn = Image.open("file/zmn.jpg")
plt.imshow(image_zmn)
plt.title('原图')
plt.axis('off')
plt.subplot(1,3,2)
image_zmn_buckle = Image.open("buckle/zmn.png")
plt.imshow(image_zmn_buckle)
plt.title('抠图处理')
plt.axis('off')
plt.subplot(1,3,3)
plt.imshow(binary_image, cmap='gray')
plt.title('二值化处理')
plt.axis('off')
plt.tight_layout()
plt.show()