我正在尝试加载多个图像,并希望自动化变量命名以制造variable name = the file input name
。
例如:
image1=read_binary('image1.img',DATA_START=0,DATA_TYPE=1,DATA_DIMS=[450, 750,3], ENDIAN=native)
只是想知道这是否可能以及如何?
您可以将所有图像名称放在字符串数组中,然后循环循环。如果您的图像为.png,则建议您使用read_png函数。这可能不是最有效的,但是如果图像的大小相同,则很容易将它们全部堆叠在一个立方体中,例如:
;Make a string array containing the names of the images
names = ['image2.png', 'image2.png', 'image3.png']
;Make a byte array to contain the x and y dimensions, the rgb, for each image
image_stack = bytarr(dimension1,dimension2,3,n_elements(names))
for i=0,n_elements(names)-1 do begin
img = READ_PNG(names[i],rpal,gpal,bpal)
image_stack[*,*,0,i] = rpal ;set r channel of image i
image_stack[*,*,1,i] = gpal ;set g channel of image i
image_stack[*,*,2,i] = bpal ;set b channel of image i
endfor
现在,您将所有图像都放在一个立方体中,其中最后一个维度是图像号。
我非常喜欢在上面概述的veda905的3D(或4D)阵列的方式中。
但是,如果您确实想为每个图像创建一个新的,独立的变量,则可以将自己的命令创建为字符串并通过Execute命令执行。
假设您在上面的数组中具有文件名:
;Make a string array containing the names of the images
names = ['image2.png', 'image2.png', 'image3.png']
; you need to supply the filename extension
varnames = FILE_BASENAME(names, '.png')
FOR i=0, N_ELEMENTS(varnames)-1 DO BEGIN
result = EXECUTE(varnames[i] + '= READ_PNG(names[' + STRING(i) + '])')
ENDFOR
哈希是为此而建立的:
h = hash()
image1 = read_binary('image1.img', data_start=0, data_type=1, $
data_dimes=[450, 750, 3], endian=native)
h['image1.img'] = image1
然后以:
检索tv, h['image1.img']
Mike的@mgalloy答案是最好的方法。
其他人可能会根据您的情况存在问题(例如,如果您有很多文件或需要在虚拟机中运行此文件),但肯定可以工作。
在哈希之前,这就是我过去的方式:
files = ['image1.img', 'image2.img', 'image3.img']
FOR i=0, N_Elements(files)-1 DO BEGIN
varName = File_BaseName(files[i], '.png')
thisImg = Read_Binary(files[i])
(Scope_VarFetch(varName), Level=0, /Enter) = thisImg
ENDFOR
Scope_VarFetch
是魔术命令,它以特定名称(以字符串给出)创建一个变量,并将数据分配给它。您还可以以类似的方式检索变量。
但是,使用IDL的一些更现代的功能要容易得多。使用哈希和foreach的相同代码?
files = ['image1.img', 'image2.img', 'image3.img']
imgs = Hash()
FOREACH, f, files Do imgs[f] = Read_Binary(files[i])
如果订单很重要,则可以使用订购的哈希