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()
标签:digit,plt,切割,img,python,image,list,import,数字
From: https://www.cnblogs.com/jinwan/p/17493298.html