python - 关于分析图像数组的唯一值
问题描述
读取图像有以下函数,我添加了几行重新输出图像,并输出图像数组的不同像素值。图像看起来像这样。然而 a,indices =np.unique(img,return_index=True)
给
[0 1]
指数 [0 879385]
看起来图像数组有两个唯一值,[0 1],这是有道理的,但索引表示什么?
def _get_image_data_pil(image_id, image_type, return_exif_md=False, return_shape_only=False):
fname = get_filename(image_id, image_type)
try:
img_pil = Image.open(fname)
except Exception as e:
assert False, "Failed to read image : %s, %s. Error message: %s" % (image_id, image_type, e)
if return_shape_only:
return img_pil.size[::-1] + (len(img_pil.getbands()),)
# -----
# this is what I adde
# -----
img = np.asarray(img_pil)
plt.imshow(img)
plt.show()
a,indices =np.unique(img,return_index=True)
print('a ',a)
print('indices ',indices)
assert isinstance(img, np.ndarray), "Open image is not an ndarray. Image id/type : %s, %s" % (image_id, image_type)
if not return_exif_md:
return img
else:
return img, img_pil._getexif()
解决方案
索引给出了扁平化输入数组中唯一值的第一次出现。要将这些索引转换为二维索引到输入,您可以使用np.unravel_index
.
例如,假设 的形状img
为 (1000, 1600):
In [110]: shape = (1000, 1600)
In [111]: indices = [0, 879385]
In [112]: np.unravel_index(indices, shape)
Out[112]: (array([ 0, 549]), array([ 0, 985]))
np.unravel_indices
返回两个数组,每个维度一个。也就是说,第一个数组保存第一维(即行)的索引,第二个数组保存第二维(即列)的索引。要将它们放入坐标数组中,您可以使用np.column_stack
:
In [113]: np.column_stack(np.unravel_index(indices, shape))
Out[113]:
array([[ 0, 0],
[549, 985]])
推荐阅读
- mysql - 带有游标和准备好的语句问题的过程:您的 SQL 语法有错误;执行语句;DEALLOCATE PREPARE stmt; 在第 34 行结束 L'
- data-structures - 具有顺序(带索引)但不允许重复的数据结构(抽象数据结构)的语义是什么?
- vue.js - Vue可点击行和href冲突
- php - 如何将此值(-16777188)转换为十六进制颜色?
- javascript - Firebase signInWithPopup 错误的网址 - 提供者未定义
- node.js - mongoose 在使用 model.find() 控制台记录数据库内项目的特定属性时返回未定义
- javascript - Firebase Firestore - 比较来自 2 个集合的数据
- reactjs - 使用 React Hooks 的多页或多步 formik 表单的类型是什么?
- python - 使用 Python 按时间戳对 CSV 文件进行排序
- python - 在 Quadpy 中积分矩阵值函数的问题