-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathImageTools.py
69 lines (49 loc) · 2.15 KB
/
ImageTools.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
from PIL import Image
from matplotlib import pyplot as plt
from torchvision import transforms
def load_image_to_tensor(image_path: str):
image = Image.open(image_path).convert("RGBA") # 读取图像并转换为RGB模式
# 如果图像有alpha通道,将RGBA图像转换为灰度图,并将透明部分填充为白色
background = Image.new("RGBA", image.size, (255, 255, 255))
alpha_composite = Image.alpha_composite(background, image)
gray_image = alpha_composite.convert("L")
# 显示灰度图像
# plt.figure(figsize=(8, 8))
# plt.imshow(gray_image, cmap='gray')
# plt.axis('off')
# plt.show()
transform = transforms.Compose([
transforms.ToTensor() # 将图像转换为PyTorch张量
])
image_tensor = transform(gray_image) # 将灰度图像转换为张量
return image_tensor
def load_image_with_alpha_channel(image_path: str):
image = Image.open(image_path).convert("RGBA") # 读取图像并转换为RGB模式
# 如果图像有alpha通道,将RGBA图像转换为灰度图,并将透明部分填充为白色
background = Image.new("RGBA", image.size, (255, 255, 255))
alpha_composite = Image.alpha_composite(background, image)
# gray_image = alpha_composite.convert("L")
# return gray_image
return alpha_composite
def convert_image_to_tensor(image_pcb):
image = image_pcb.convert("RGBA") # 读取图像并转换为RGB模式
# 如果图像有alpha通道,将RGBA图像转换为灰度图,并将透明部分填充为白色
background = Image.new("RGBA", image.size, (255, 255, 255))
alpha_composite = Image.alpha_composite(background, image)
gray_image = alpha_composite.convert("L")
# 显示灰度图像
# plt.figure(figsize=(8, 8))
# plt.imshow(gray_image, cmap='gray')
# plt.axis('off')
# plt.show()
transform = transforms.Compose([
transforms.ToTensor() # 将图像转换为PyTorch张量
])
image_tensor = transform(gray_image) # 将灰度图像转换为张量
return image_tensor
def display_image(image):
plt.imshow(image)
plt.axis('off')
plt.show()
def convert_to_rgb(img):
return img.convert('RGB')