在深度学习或图像处理项目中,准确的图像标注是模型训练的关键。但如何直观验证我们的TXT标签是否完美贴合图像实例呢?今天,就来揭秘一个高效小技巧,让你轻松实现标签与图像的无缝对接!👀
🚀 需求场景: 想象一下,你有一堆珍贵的图像数据,每个图像都配有一个TXT文件,里面详细记录了图像中的对象位置、类别等信息。手动一一核对这些标签是否精准无误,听起来就像是一场马拉松式的挑战。但别担心,借助几行简洁的代码,我们可以让这一切自动化,一目了然!
💻 实现步骤:
-
读取TXT文件: 利用Python的
pandas
或直接使用open()
读取TXT文件,解析出标签信息,如边界框坐标、类别ID等。 -
加载图像: 利用
OpenCV
或PIL
库加载对应的图像。 -
绘制标签: 根据TXT中的信息,在图像上绘制边界框、类别标签或甚至遮罩。比如,使用
cv2.rectangle()
画框,cv2.putText()
添加文字描述。 -
显示图像: 最后,用
cv2.imshow()
展示这张带标签的图像,一眼辨真伪!
实例分割的可视化:
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
# 读取文件
with open('E://txt', 'r') as file:# 标签路径
lines = file.readlines()
# 解析数据并转换为绝对像素坐标
data = []
image_path = 'E://png' # 图像路径
image = Image.open(image_path)
width, height = image.size
for line in lines:
parts = line.strip().split()
if parts:
category = int(parts[0])
# 将相对坐标转换为绝对像素坐标
abs_coords = np.array(parts[1:], dtype=float).reshape(-1, 2) * [width, height]
data.append((category, abs_coords))
# 显示图像并标注点
fig, ax = plt.subplots(figsize=(10, 10)) # 可以根据需要调整figsize
ax.imshow(image)
colors = ['r', 'g', 'b', 'y', 'm', 'c']
for idx, (category, coords) in enumerate(data):
ax.scatter(coords[:, 0], coords[:, 1], color=colors[category % len(colors)], label=f'Category {category}', s=30)
# 隐藏坐标轴
ax.axis('off')
# 添加图例
plt.legend(loc='upper right', bbox_to_anchor=(1, 1), fontsize='small')
plt.tight_layout()
plt.show()
最后可视化结果如下
目标检测的可视化:
import cv2
import pandas as pd
# 读取TXT文件
txt_path = 'example.txt'
with open(txt_path, 'r') as file:
annotations = file.readlines()
# 加载图像
image_path = 'example.jpg'
image = cv2.imread(image_path)
# 解析标签并绘制
for annotation in annotations:
class_id, x, y, width, height = map(float, annotation.strip().split(',')) # 假设TXT格式为"classID,x,y,width,height"
x, y, width, height = int(x * image.shape[1]), int(y * image.shape[0]), int(width * image.shape[1]), int(height * image.shape[0])
cv2.rectangle(image, (x, y), (x+width, y+height), (0, 255, 0), 2) # 绘制边界框
cv2.putText(image, f'Class {int(class_id)}', (x, y-5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2) # 添加类别标签
# 显示图像
cv2.imshow('Labeled Image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
🎯 小结: 通过上述步骤,你可以在数秒内将TXT标签直观地映射到图像上,大大提升了校验效率,确保每一个标注都能精确无误地对应到图像实例上。无论是科研项目还是工业应用,这项技能都将成为你提升工作效率的秘密武器!🔥