image - 如何在不改变像素值的情况下对图像数组进行采样

标签 image python-imaging-library scikit-image cv2 ndimage

我有图像分割项目,以及以像素值代表标签的图像形式给出的地面实况标签。我需要调整图像和标签的大小,同时将标签保持在相同的值集中。

我尝试了很多东西,都改变了值集。

让我们创建虚拟数据

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]

关于image - 如何在不改变像素值的情况下对图像数组进行采样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50038263/

相关文章:

python - pil 绘制不同颜色的文本

python - 为什么在 for 循环中使用 PIL 的 Image.paste 时出现图像重叠问题?

python - 由于图像杂质,skimage 峰值局部最大值发现多个非常接近的点

php - 如何删除位于 img/p/的 Prestashop 无用图像

python - 尝试使用 kairos 上传文件时出错

Python pytesseract - 找不到 eng.traineddata -- oem 2

python - Flask Web 服务器在处理和上传到 S3 时损坏图像

php - 图片 - 上传没有响应,无法访问 $_FILES

python - 多维数组/准图像的连通分量标记

python - 为什么高斯滤波器在 cv2 和 skimage 之间不同?