【发布时间】:2020-05-26 12:31:44
【问题描述】:
我想找到最多几个图像:将它们加载到一个数组中并在第一维上找到一个最大值。
Python 代码示例:
import cv2
import sys
import numpy as np
imgs_paths = sys.argv[1:]
imgs = list(map(cv2.imread, imgs_paths))
imgs_arr = np.array(imgs, dtype=np.float32)
imgs_max = np.max(imgs_arr, 0)
我所做的如下:
using Colors, Images
function im_to_array(im)
img_array = permutedims(channelview(im), (2,3,1))
img_array = Float32.(img_array)
return img_array
end
imgs = map(Images.load, imgs_paths)
imgs_arr = map(im_to_array, imgs)
a = imgs_arr
b = reshape(cat(a..., dims=1), tuple(length(a), size(a[1])...))
imgs_max = maximum(b, dims=1)
但它很丑。
我找到了更简单的方法来获得最大值(代码如下),但它的性能很糟糕。可能不是我所期待的。
function im_to_array(im)
img_array = permutedims(channelview(im), (2,3,1))
img_array = Float32.(img_array)
return img_array
end
imgs = map(Images.load, imgs_paths)
imgs_arr = map(im_to_array, imgs)
imgs_max = max.(imgs_arr...)
第一种方法在 120 个全高清图像上的运行时间在我的笔记本电脑上约为 5 秒。而且我无法确定第二种方法的运行时间,因为我等待了大约 30 分钟并且它没有停止。我在 Julia 1.4.1 上测试它
有没有更好的方法来查找最多多个图像?
UPD:这是我想要的简单案例:
a = [zeros(Int8, 8, 8, 3), zeros(Int8, 8, 8, 3), zeros(Int8, 8, 8, 3)] # 3 black images with shape 8x8
max.(a) #doesn't work
max.(a...) #works with this simple input but when I test it on 120 FHD images it's extremely slow
UPD2:我在少量图像上测试了这两种方法。
function max1(imgs_arr)
a = imgs_arr
b = reshape(cat(a..., dims=1), tuple(length(a), size(a[1])...))
imgs_max = maximum(b, dims=1)
return imgs_max
end
function max2(imgs_arr)
return max.(imgs_arr...)
end
imgs_arr = my_imgs_arrays[1:5]
@time max1(imgs_arr)
@time max2(imgs_arr)
0.247060 seconds (5.29 k allocations: 142.657 MiB)
0.154158 seconds (44.85 k allocations: 26.388 MiB)
imgs_arr = my_imgs_arrays[1:15]
@time max1(imgs_arr)
@time max2(imgs_arr)
0.600093 seconds (72.38 k allocations: 382.923 MiB)
0.769446 seconds (1.24 M allocations: 71.374 MiB)
imgs_arr = my_imgs_arrays[1:25]
@time max1(imgs_arr)
@time max2(imgs_arr)
1.057548 seconds (23.08 k allocations: 618.309 MiB)
5.270050 seconds (151.52 M allocations: 2.329 GiB, 4.77% gc time)
所以,我使用的图片越多,效果就越慢。
【问题讨论】:
-
我不确定你在执行什么操作,第一个维度是
x维度还是来自python的“图像编号”维度? -
@FredrikBagge,是的,我想沿“图像编号”维度计算
max -
@FredrikBagge,我在问题中添加了简单的案例。可能是 Julia 优化/性能问题,我应该在 Julia 社区中询问它?
标签: arrays image-processing julia