Я хочу найти максимум несколько изображений: загрузить их в массив и найти максимум по первому измерению.
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 изображениях FHD на моем ноутбуке составляет ~ 5 секунд. И я не могу определить время выполнения второго метода, потому что я ждал ~ 30 минут, и он не прекращался. Тестирую на Юлии 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)
Итак, больше изображений использую - медленнее работает.