我想在带有 np.where 的 numpy 数组中找到唯一的颜色元组。到目前为止我的代码是:
from __future__ import print_function
import numpy as np
a = range(10)
b = range(10,20)
c = range(20,30)
d = np.array(zip(a, b, c))
print(d)
e = np.array(zip(c, b, a))
print(e)
search = np.array((1,11,21))
search2 = np.array((0,11,21))
print(search, search2)
f = np.where(d == search, d, e)
g = np.where(d == search2, d, e)
print(f)
print(g)
当我运行代码时,它正确地找到了第二个位置的元组搜索。但是元组 search2 也位于第一个位置,尽管它没有作为唯一的元组包含在数组中。我如何在 numpy 中定义在数组中只能找到唯一的元组,以便为 g 提供一些值
[[20 10 0] [21 11 1] [22 12 2]
[23 13 3] [24 14 4] [25 15 5]
[26 16 6] [27 17 7] [28 18 8] [29 19 9]]
但仍然找到唯一的元组搜索并给出 f
[[20 10 0] [ 1 11 21] [22 12 2]
[23 13 3] [24 14 4] [25 15 5]
[26 16 6] [27 17 7] [28 18 8] [29 19 9]]
?
编辑:
OK,那么现在的问题是用python写一个GIF解码器。我有一个名为 image_a 的前一帧和一个名为 image_b 的后一帧。image_b 包含具有特定透明度颜色元组的像素,在这种特定情况下,对于上传的图像称为 transp_color,它是 (0, 16, 8)。该例程应该用来自 image_a 的像素值的颜色元组替换所有这些条目,但保持其他像素不变。我的代码是:
from __future__ import print_function
import numpy as np
import cv2
image_a = cv2.imread("old_frame.png")
image_b = cv2.imread("new_frame.png")
cv2.imshow("image_a", image_a)
cv2.imshow("image_b", image_b)
transp_color = (0, 16, 8)
new_image = np.where(image_b == transp_color, image_a, image_b)
cv2.imshow("new_image", new_image)
cv2.waitKey()
尝试使用 np.where 解决这个问题会导致结果图像中的颜色错误,如上图 3 所示。那么知道如何解决这个问题吗?
好的,终于自己找到了解决方案,下面是代码:
import numpy as np
import cv2
image_a = cv2.imread("old_frame.png")
image_b = cv2.imread("new_frame.png")
cv2.imshow("image_a", image_a)
cv2.imshow("image_b", image_b)
transp_color = (0, 16, 8)[::-1]
channels = 3
f = np.all((image_b==transp_color), axis=-1)
flattened_image = np.reshape(image_b, (image_b.shape[0]*image_b.shape[1], channels))
old_flattened_image = np.reshape(image_a, (image_a.shape[0]*image_a.shape[1], channels))
f = np.reshape(f, (image_a.shape[0]*image_a.shape[1], 1))
np_image = np.array([old_flattened_image[i] if j else flattened_image[i] for i, j in enumerate(f)])
new_image = np.reshape(np_image, (image_a.shape[0], image_a.shape[1], channels))
# new_image = np.where(image_b == transp_color, image_a, image_b)
cv2.imshow("new_image", new_image)
cv2.waitKey()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句