如何在python中绘制二进制数据?

时间:2017-05-24 06:11:50

标签: python matplotlib binary-data data-conversion

首先,我知道我的问题经常被问到。但我还没有找到解决方案。

我使用USBTMC来控制示波器。 Here您可以找到有关它的更多信息。我能够捕获屏幕并将其写入文件(见图)。但我希望每隔n秒实时绘制一次屏幕。我想用matplotlib.pyplot作为例子。

enter image description here

这是我的代码(绝望地尝试使用pyplot绘制数据):

import usbtmc
from time import sleep 
import matplotlib.pyplot as plot
import numpy as np
import subprocess

maxTries = 3

scope = usbtmc.Instrument(0x0699, 0x03a6)
print scope.ask("*IDN?")

scope.write("ACQ:STOPA SEQ")
scope.write("ACQ:STATE ON")

while ( True ):
  #get trigger state  
  trigState = scope.ask("TRIG:STATE?")
  #check if Acq complete 
  if ( trigState.endswith('SAVE') ):
    print 'Acquisition complete. Writing into file ...'
    #save screen
    scope.write("SAVE:IMAG:FILEF PNG")
    scope.write("HARDCOPY START")

    #HERE I get binary data
    screenData = scope.read_raw()

    #HERE I try to convert it?
    strData = np.fromstring( screenData, dtype=np.uint8 )

    #HERE I try to plot previous
    plot.plot( strData )
    plot.show()

    #rewrite in file (this works fine) 
    try:
      outFile = open("screen.png", "wb")
      outFile.write( screenData )
    except IOError:
      print 'Error: cannot write to file'
    else:
      print 'Data was written successfully in file: ', outFile.name
    finally:
      outFile.close()
 #continue doing something

运行此代码后,我得到......看看图片。 enter image description here

1 个答案:

答案 0 :(得分:1)

不幸的是我无法测试它,但你可以尝试这样的事情

import io

screenData = scope.read_raw()
arrayData = plt.imread(io.BytesIO(screenData))
plt.imshow(arrayData)
plt.show()

我想要注意的是,对于实时绘图,最好不要从示波器屏幕获取图像,而是原始数据。这应该允许更快的操作。