import torch
import torch.nn as nn
from torchvision import transforms
from PIL import Image, ImageOps
import numpy as np
img = Image.open("QQ.png")
img

def CutImage(img):
img = img.convert("L")
threshold = 128
img = img.point(lambda x: 0 if x > threshold else 255)
width, height = img.size
images = []
images2828 = []
in_digit = False
left = 0
top = height
bottom = 0
for x in range(width):
has_black = False
for y in range(height):
pixel = img.getpixel((x, y))
if pixel == 0:
has_black = True
top = min(top, y)
bottom = max(bottom, y)
if has_black and not in_digit:
in_digit = True
left = x
if not has_black and in_digit:
in_digit = False
right = x
image = img.crop((left, top, right, bottom))
image = ImageOps.invert(image)
images.append(image)
for obj in images:
if 4 * obj.size[0] <= obj.size[1]:
zero_matrix = np.zeros((obj.size[1], 4 * obj.size[0]))
result_matrix = np.concatenate((zero_matrix, obj, zero_matrix), axis=1)
resized_image = Image.fromarray(result_matrix).resize((28, 28), resample=Image.Resampling.NEAREST)
images2828.append(resized_image)
continue
obj = np.pad(np.asarray(obj), pad_width=20, mode='constant', constant_values=0)
resized_image = Image.fromarray(obj).resize((28, 28), resample=Image.Resampling.NEAREST)
images2828.append(resized_image.convert('F'))
return images2828
image_list = CutImage(img)
image_list
[<PIL.Image.Image image mode=F size=28x28>,
<PIL.Image.Image image mode=F size=28x28>,
<PIL.Image.Image image mode=F size=28x28>,
<PIL.Image.Image image mode=F size=28x28>,
<PIL.Image.Image image mode=F size=28x28>,
<PIL.Image.Image image mode=F size=28x28>,
<PIL.Image.Image image mode=F size=28x28>,
<PIL.Image.Image image mode=F size=28x28>,
<PIL.Image.Image image mode=F size=28x28>]
import matplotlib.pyplot as plt
plt.imshow(image_list[0], cmap='gray')
plt.show()

plt.imshow(image_list[1], cmap='gray')
plt.show()

plt.imshow(image_list[2], cmap='gray')
plt.show()

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异