【发布时间】:2018-03-19 17:17:04
【问题描述】:
所以对于我正在做的一些机器学习工作,我需要能够生成随机图像并将它们添加到现有图像中。为了测试,我生成这些随机图像并将它们乘以零,然后将它们添加到我现有的图像中。我希望收到与原始图像相同的新图像,但我会收到原始图像的蓝色版本:
我已经为此苦苦思索了好几个小时,似乎无法就造成这种差异的原因得出结论。以下是相关代码:
# unit_img is an ndarray with random entries, then normalized
# so that the sum of the squares of all the elements is 1
# min_dist is our scalar we multiply our unit image by, since
# it's zero we don't care about the unit image
min_dist = 0
...
unit_img = np.load(path_to_unit_img)
unit_img = min_dist * unit_img
# check if our unit img and our original image are the same size
if unit_img.size != checked_img.size:
continue
# "move" our new image to the solution space of the original img
addition = unit_img + checked_img
result_img = Image.fromarray(addition.astype('uint8')).convert('RGB')
# now we save our generated image
result_img.save(save_path + extension + img[:-4] + "_" + str(x) + ".jpg")
为了全面披露,我迭代了几千张图片,每张图片的 unit_img 都不同。运行一个简单的测试程序,加载上面显示的两个猫图像并将它们打印出来,我看到了:
# original image
[[[164 159 160]
[164 159 160]
[164 159 160]
...
[152 152 152]
[152 152 152]
[152 152 152]]
[[165 160 161]
[165 160 161]
[165 160 161]
...
[152 152 152]
[152 152 152]
[152 152 152]]
[[162 160 160]
[162 160 160]
[162 160 160]
...
[152 152 152]
[152 152 152]
[152 152 152]]
...
[[151 143 136]
[151 143 136]
[151 143 136]
...
[ 81 81 81]
[ 83 83 83]
[ 85 85 85]]
[[152 144 137]
[152 144 137]
[152 144 137]
...
[ 86 86 86]
[ 83 83 83]
[ 82 82 82]]
[[152 144 137]
[152 144 137]
[152 144 137]
...
[ 89 89 89]
[ 82 82 82]
[ 78 78 78]]]
===========================================
# Resultant from adding an array of zeros
[[[160 159 163]
[160 159 163]
[160 159 163]
...
[152 152 152]
[152 152 152]
[152 152 152]]
[[161 160 164]
[161 160 164]
[161 160 164]
...
[152 152 152]
[152 152 152]
[152 152 152]]
[[160 159 161]
[160 159 161]
[160 159 161]
...
[152 152 152]
[152 152 152]
[152 152 152]]
...
[[137 143 150]
[137 143 150]
[137 143 150]
...
[ 80 80 80]
[ 83 83 83]
[ 87 87 87]]
[[138 144 151]
[138 144 151]
[138 144 151]
...
[ 86 86 86]
[ 83 83 83]
[ 82 82 82]]
[[138 144 151]
[138 144 151]
[138 144 151]
...
[ 89 89 89]
[ 82 82 82]
[ 77 77 77]]]
很明显,这些图像在数值上是相似的,但沿途有些轴倒置了。到目前为止,我尝试的是检查我的 unit_img 是否发布
unit_img = min_dist * unit_img
通过执行 np.count_nonzero 确实为零,并且它始终具有 0 个非零元素,这意味着我实际上是在添加一个充满零的 ndarray。这意味着我以某种方式错误地保存了图像,或者可能是错误的数据类型。任何帮助都将不胜感激!
【问题讨论】:
-
您是否检查过要加在一起的两个数组是否包含相同类型的数据?另一种可能性是零数组具有与原始图像不同的维度(可能是第 3 个/颜色)。随着 uint8 添加和色彩空间转换,某些内容可能会在翻译中丢失。最好分别执行这些步骤并检查每个步骤。
-
什么是
type(checked_img)? (显示该函数调用的确切结果。)如果它是一个 numpy 数组,checked_img.dtype是什么? -
您将结果保存为 JPEG 文件。这是一种有损格式,因此只需将其保存在新文件中即可对其进行更改。尝试使用无损格式,例如 PNG。
-
我会考虑切换到 PNG 谢谢!但特别是对于轴反转,结果证明 cv2.imread 正在读入 BGR 而不是 RGB np 数组。谢谢大家!
标签: python numpy python-imaging-library