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

2019-07-22 15:07发布

问题:

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.