如何将ASCII数组(图像)转换为单个字符串 [英] How to convert ASCII array (image) to a single string
问题描述
我的元数据存储在HDF5文件中的8位无符号数据集中。导入到DM后,它将成为1 *长度尺寸的2D图像。每个像素将相应值的ASCII值存储到字符中。
为了进一步处理,我必须将ASCII数组转换为单个字符串,然后转换为TagGroup。这是我目前做的愚蠢的方法(逐个像素):
My metadata is stored in a 8 bit unsigned dataset in a HDF5 file. After importing to DM, it become a 2D image of 1*length dimension. Each "pixel" stores the ASCII value of the corresponding value to the character. For further processing, I have to convert the ASCII array to a single string, and further to TagGroup. Here is the stupid method (pixel by pixel) I currently do:
String Img2Str (image img){
Number dim1, dim2
img.getsize(dim1,dim2)
string out = ""
for (number i=0; i<dim1*dim2; i++)
out += img.getpixel(0,i).chr()
Return out
}
这种像素操作非常慢!有没有其他更快的方法来完成这项工作?
This pixel-wise operation is really quite slow! Is there any other faster method to do this work?
推荐答案
是的,还有更好的方法。你真的想看一下原始数据流的章节:
Yes, there is a better way. You really want to look into the chapter of raw-data streaming:
如果您在stream对象中保存原始数据,则可以以任何您喜欢的形式进行读取和写入。所以你的问题的解决方案是
If you hold raw data in a "stream" object, you can read and write it in any form you like. So the solution to your problem is to
- 创建一个流
- 添加图像到流(写入二进制数据)
- 将蒸汽位置重置为开始
- 读取二进制数据字符串
- Create a stream
- Add the "image" to the stream (writing binary data)
- Reset the steam position to the start
- Read out the binary data a string
这是代码:
{
number sx = 10
number sy = 10
image textImg := IntegerImage( "Text", 1, 0 , sx, sy )
textImg = 97 + random()*26
textImg.showimage()
object stream = NewStreamFromBuffer( 0 )
ImageWriteImageDataToStream( textImg, stream, 0 )
stream.StreamSetPos(0,0)
string asString = StreamReadAsText( stream, 0, sx*sy )
Result("\n as string:\n\t"+asString)
}
请注意,您可以创建链接到光盘上文件的流,如果您知道起始位置(以字节为单位),也可以直接从文件中读取。
Note that you could create a stream linked to file on disc and, provided you know the starting position in bytes, read from the file directly as well.
这篇关于如何将ASCII数组(图像)转换为单个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!