How to convert ASCII array (image) to a single string

天涯浪子 提交于 2019-12-24 06:37:58

问题


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?


回答1:


Yes, there is a better way. You really want to look into the chapter of raw-data streaming:

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

This is the code:

{
    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.



来源:https://stackoverflow.com/questions/39719129/how-to-convert-ascii-array-image-to-a-single-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!