如何调整样本图像数组,而无需更改像素值



我有图像分割项目,并且给出的地面真实标签为图像,其中像素值代表标签。我需要调整图像和标签大小,同时将标签保持在相同的值集中。

我尝试了很多事情,都更改了值集。

让我们创建虚拟数据

from skimage.transform import rescale, resize
from scipy import ndimage
from PIL import Image
import cv2
mask = np.zeros((30,20), dtype=np.uint16)
mask[22:26,12:30]=70
mask[25:27,14:17]=30
print('original label', mask.shape, np.unique(mask))
输出:原始标签形状:(30,20(原始标签值: [0 30 70]

我需要调整标签大小,因此结果只有0、30、70值

我尝试的
skimage_resized = resize(mask, (mask.shape[0]//2, mask.shape[1]//2), mode='constant')
print(skimage_resized.shape, np.unique(mask_resized))
skimage_rescale = rescale(mask, 1.0/2.0, mode='constant')
print(skimage_rescale.shape, np.unique(mask_resized))
ndimage_resized = ndimage.interpolation.zoom(mask, 0.5)
print(ndimage_resized.shape, np.unique(mask_resized))

cv2_resized = cv2.resize(mask, (mask.shape[0]//2, mask.shape[1]//2),
                        interpolation=cv2.INTER_NEAREST)
print(cv2_resized.shape, np.unique(mask_resized))
mask_pil = Image.fromarray(mask, mode=None)
pil_resized = mask_pil.thumbnail((mask.shape[0]//2, mask.shape[1]//2), Image.NEAREST)
print(skimage_resized.shape, np.unique(pil_resized))

输出:

(15, 10) [ 0  5  6 28 29 30 31 61 62 65 70 71 74 75 76]
(15, 10) [ 0  5  6 28 29 30 31 61 62 65 70 71 74 75 76]
(15, 10) [ 0  5  6 28 29 30 31 61 62 65 70 71 74 75 76]
(10, 15) [ 0  5  6 28 29 30 31 61 62 65 70 71 74 75 76]
(15, 10) [None]

找到了使用OpenCV的解决方案。

import numpy as np
import cv2
resizeto = 2
small_lable = cv2.resize(mask, (mask.shape[1]//resizeto, 
                         mask.shape[0]//resizeto),
                        interpolation=cv2.INTER_NEAREST)
small_lable = (np.array(small_lable)).astype('uint8')
print(small_lable.shape, np.unique(small_lable))
plt.imshow(small_lable)

输出:

(15, 10) [ 0 30 70]

来自文档(重点是我的(:

请注意,在减小图像时,调整大小和恢复时应执行高斯平滑,以避免使伪像辩护。请参阅对这些功能的抗_aliasing和anti_aliasing_sigma参数。

降尺度的目的是使用整数因子使用局部平均值在每个尺寸因子的元素上作为函数的参数进行 local Mean 对n维图像进行下采样。/blockquote>

解决问题的一种可能的解决方法是通过基本切片来删除采样:

import numpy as np
dx, dy = 2, 2
mask = np.zeros((30, 20), dtype=np.uint16)
mask[22:26, 12:30] = 70
mask[25:27, 14:17] = 30
downsampled = mask[::dx, ::dy]
print(downsampled.shape, np.unique(downsampled))

上面片段的输出是:

(15, 10) [ 0 30 70]

最新更新