Coding-图像处理

恢复将归一化后的图片

变换

1
2
3
4
5
6

transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])

存储验证集中预测错误的图片

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
with torch.no_grad():
for images, labels in val_loader:
images = images.to(device)
labels = labels.to(device)

outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total_samples += labels.size(0)
total_correct += (predicted == labels).sum().item()

# 找出识别错误的图片
misclassified_idx = (predicted != labels)
misclassified_images.extend(images[misclassified_idx].cpu().numpy())

val_accuracy = total_correct / total_samples
print(f"Validation Accuracy: {val_accuracy:.4f}")


# 保存识别错误的图片
for i, image in enumerate(misclassified_images):
image = np.transpose(image, (1, 2, 0)) # 转换为通道在最后的形式
image = (image * [0.229, 0.224, 0.225] + [0.485, 0.456, 0.406]) * 255 #恢复过程
image = image.astype(np.uint8) # 将像素值还原为 0-255 范围
image = Image.fromarray(image)
image.save(f"error_images/misclassified_{epoch}_{i}.jpg")

多线程压缩图片

将输入文件夹里的图片压缩有存储到输出文件夹中

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
import os
import shutil
from concurrent.futures import ThreadPoolExecutor
from PIL import Image

input_folder = 'input_folder'
output_folder = 'output_folder'

# 创建输出文件夹
if not os.path.exists(output_folder):
os.makedirs(output_folder)

# 获取输入文件夹中所有图片文件的文件名
file_names = [f for f in os.listdir(input_folder) if os.path.isfile(os.path.join(input_folder, f)) and any(f.endswith(ext) for ext in ['.jpg', '.jpeg', '.png', '.bmp', '.gif'])]

def process_image(file_name):
# 获取输入文件的路径
input_file_path = os.path.join(input_folder, file_name)
output_file_path = os.path.join(output_folder, file_name)

# 打开图片文件
with Image.open(input_file_path) as image:
# 检查图片格式
if image.format in ['JPEG', 'JPG', 'PNG']:
# 压缩图片并保存到输出文件夹
compressed_image = image.copy()
compressed_image.save(output_file_path, optimize=True, quality=25)

# 检查图片大小是否超过500KB
while os.path.getsize(output_file_path) > 500 * 800:
# 缩小图片尺寸
width, height = compressed_image.size
new_width = int(width * 0.9)
new_height = int(height * 0.9)
compressed_image = compressed_image.resize((new_width, new_height))

# 保存压缩后的图片
compressed_image.save(output_file_path, optimize=True, quality=25)

# 使用ThreadPoolExecutor来并行处理每一张图片
with ThreadPoolExecutor() as executor:
executor.map(process_image, file_names)

其他格式图片转JPG

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
import os
from PIL import Image

def convert_to_jpg(input_path, output_path):
with Image.open(input_path) as image:
# 转换为JPEG格式并保存
rgb_image = image.convert("RGB")
rgb_image.save(output_path, format="JPEG")

def convert_images_to_jpg(input_folder, output_folder):
# 如果输出文件夹不存在,则创建该文件夹
if not os.path.exists(output_folder):
os.makedirs(output_folder)

# 遍历文件夹下的所有子文件夹和文件
for root, dirs, files in os.walk(input_folder):
for file in files:
# 获取文件的完整路径
input_path = os.path.join(root, file)

# 检查文件是否为图片格式
if file.lower().endswith(('.png', '.bmp', '.gif', '.tiff')):
# 构建输出路径
output_path = os.path.join(output_folder, os.path.splitext(file)[0] + '.jpg')

# 将文件转换为JPEG格式
convert_to_jpg(input_path, output_path)

# 设置输入和输出文件夹路径
input_folder = 'input_folder'
output_folder = 'output_folder'

# 转换图片格式为JPEG
convert_images_to_jpg(input_folder, output_folder)

将文件夹下的三通道图片转为单通道

1
2
3
4
5
6
7
8
9
10
11
12
from PIL import Image
import os
path = 'input_floder'

list_ = os.listdir(path)

list_ = [ os.path.join(path,i) for i in list_]

for i in list_:
image = Image.open(i)
gray_image = image.convert('L')
gray_image.save(i)