【图像算法的图片预处理流程】 https://www.bilibili.com/video/BV1Po4y167Zz/?share_source=copy_web&vd_source=eb362ca89a4fdf852de4d875f6327898
简单流程:3个步骤(中间3个)
1.opencv读取图片
2.resize操作:把原图读进去,将图片等比例缩放(找大的变成按要求缩放),然后放到灰度图像中,形成拼接图像

3.归一化标准化处理:使预测效果不会因图片差异化影响

4.图片由BGR格式转化为RGB格式:人眼看不懂BGR,看得懂RGB

5.输入模型
实验代码:
(前提安装,window+R,输入下面两个,可能还有其他的库)
pip install opencv-python
pip install matplotlib
将要处理的图片放到pycharm的项目中

import cv2
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
# 解决中文显示问题
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
# 预设参数
test_size = (640, 640) # 目标尺寸(高度, 宽度)
rgb_means = (0.485, 0.456, 0.406)
std = (0.229, 0.224, 0.225)
fill_color = 114 # YOLO填充颜色
def preproc_visualize(image, input_size, mean, std, fill_color):
"""可视化图像预处理全流程"""
plt.figure(figsize=(15, 10))
steps = [] # 存储各步骤图像和标题
# 1. 原始图像(BGR格式,OpenCV读取)
steps.append(("1. 原始图像 (BGR)", image))
# 2. 计算缩放比例并Resize
h, w = image.shape[:2]
r = min(input_size[0] / h, input_size[1] / w)
resized_h = int(h * r)
resized_w = int(w * r)
resized_img = cv2.resize(image, (resized_w, resized_h), interpolation=cv2.INTER_LINEAR)
steps.append(("2. 缩放后图像 (保持比例)", resized_img))
# 3. 创建填充背景并粘贴缩放图像
if len(image.shape) == 3:
padded_img = np.full((input_size[0], input_size[1], 3), fill_color, dtype=np.uint8)
else:
padded_img = np.full(input_size, fill_color, dtype=np.uint8)
padded_img[:resized_h, :resized_w] = resized_img
steps.append(("3. 填充至目标尺寸", padded_img))
# 4. BGR转RGB(Matplotlib显示需要RGB格式)
rgb_img = padded_img[:, :, ::-1]
steps.append(("4. BGR转RGB", rgb_img))
# 5. 归一化(除以255)
normalized_img = rgb_img.astype(np.float32) / 255.0
steps.append(("5. 归一化 (0-1)", normalized_img))
# 6. 标准化(减均值、除标准差)
standardized_img = (normalized_img - mean) / std
steps.append(("6. 标准化", standardized_img))
# 可视化所有步骤
for i, (title, img) in enumerate(steps):
plt.subplot(2, 3, i + 1)
plt.title(title)
# 处理不同数据类型的显示
if img.dtype == np.uint8:
plt.imshow(img)
else:
# 标准化后数值可能超出0-1,需归一化到可显示范围
img_display = (img - img.min()) / (img.max() - img.min() + 1e-8)
plt.imshow(img_display, cmap="gray" if len(img.shape) == 2 else None)
plt.axis('off')
plt.tight_layout()
plt.show()
return standardized_img # 返回最终处理结果
if __name__ == "__main__":
img_path = "caomei.png"
image = cv2.imread(img_path)
if image is None:
print("错误:无法读取图像,请检查路径。")
else:
processed_img = preproc_visualize(image, test_size, rgb_means, std, fill_color)
运行结果:


6749

被折叠的 条评论
为什么被折叠?



