首页 > 解决方案 > Python:水平翻转图像并重新排序目标

问题描述

我正在关注这个 关于面部关键点检测(由 (x,y) 目标坐标标识)的数据集数据增强教程。

我想水平翻转图像,因此也需要以这种方式交换一些目标:

left_eye_center_x --------->> right_eye_center_x
left_eye_center_y --------->> right_eye_center_y
left_eye_inner_corner_x --------->> right_eye_inner_corner_x
left_eye_inner_corner_y --------->> right_eye_inner_corner_y
...

打印时图像翻转和坐标重新排序似乎很好,但在绘图时却不行

代码:

# target indices to swap
flip_indices = [(0, 2), (1, 3),(4, 8), (5, 9), (6, 10), (7, 11), (12, 16),
                (13, 17), (14, 18), (15, 19),(22, 24), (23, 25)]

# permutation that represents the target coordinates reordering
permutation = [2, 3, 0, 1, 8, 9, 10, 11, 4, 5,
              6, 7 ,16, 17, 18, 19, 12, 13, 14, 15,
              20, 21, 24, 25, 22, 23, 26, 27, 28, 29]

X_train_flipped = np.flip(X_train, axis=2) # flips images horizontally
Y_train_flipped = np.copy(Y_train)[:,permutation] # flips targets according to permutation

print (Y_train[1,permutation] == Y_train_flipped[1]) # permutation seems successful    

fig = plt.figure(figsize=(10, 10))
# original image, original targets
ax = fig.add_subplot(1, 3, 1, xticks=[], yticks=[])
plot_sample(X_train[1], Y_train[1], ax)

# flipped image, original targets
ax = fig.add_subplot(1, 3, 2, xticks=[], yticks=[])
plot_sample(X_train_flipped[1], Y_train[1], ax)

# flipped image, flipped targets
ax = fig.add_subplot(1, 3, 3, xticks=[], yticks=[])
plot_sample(X_train_flipped[1], Y_train_flipped[1], ax)

输出:

[ True  True  ... True  True]

第三张图片应正确定位目标。 在此处输入图像描述

该函数plot_sample()在教程中定义如下:

def plot_sample(x, y, axis):
    img = x.reshape(96, 96) 
    axis.imshow(img, cmap='gray') 

    axis.scatter(y[0::2] * 48 + 48, y[1::2] * 48 + 48, marker='x', s=10)

标签: pythonnumpymatplotlibmachine-learning

解决方案


推荐阅读