0

I am trying to make an interactive plot of the tangent line using matplotlib and cv2. Before, I was just saving the files to my disk, then opening the images as .png into a list of images. I decided to omit using the disk and use a cStringIO buffer. I've ommitted the image display loop for now because I'm quite certain it will work when I get past this. I have two functions, pic() generates the plot, then calls convt() to convert the plot into a buffer, and extracts the raw string using buff.getValue, then returns the string. The problem seems to be with np.frombuffer(). If I just print pic() I can see the buffer as a string, but np.frombuffer(pic()) causes the ValueEerror:

ValueError: buffer size must be a multiple of element size

Here are the two functions and the commented out loop to fill the list. The math function definitions have been left out because I already tested them and they work as intended. Note, this version is minimized to cause the same error:

from matplotlib import pyplot as plt
import numpy as np
from cStringIO import StringIO 
js= lambda t: 3*t    #define function
ts=np.linspace(-3,3,100)   #define domain

def convt(fig):
    buff=StringIO()  #instantiate StringIO object
    fig.savefig(buff, format='png', dpi=fig.dpi)  #print png to buffer
    rawstring=buff.getvalue()   #pull string from buffer
    buff.close() #close buffer
    return rawstring  #return string

def pic(ts,js):
    plt.plot(ts,js(ts))  #generate mpl plot
    fig=plt.gcf()   #grab current figure
    out=convt(fig)  #convert to string
    plt.close()     #close plot
    return out      #return string

np.frombuffer(rawstring) #causes ValueError, remove np.frombuffer()
                         #and you can see the string
ThisGuyCantEven
  • 1,095
  • 12
  • 21
  • What is the purpose of this code? Why do you need to create a pixel image at all? Can you provide a [mcve] please (most of the code seems irrelevant for the actual problem)? – ImportanceOfBeingErnest Aug 23 '17 at 22:38
  • I have narrowed the problem down to this, the purpose of these two functions are to generate a `matplotlib` object , save it to a string buffer, then convert that buffer to a pixel array for `cv2.imshow`. The commented out loop saves those arrays to a list, which I can decode and show in the window based on a slider position. Additionally, the comments are very descriptive. – ThisGuyCantEven Aug 23 '17 at 22:56
  • I have minimized this as per your request Ernest. – ThisGuyCantEven Aug 23 '17 at 23:07
  • Ok, I was asking because I'm not sure why you need to save the image at all. Is [this question](https://stackoverflow.com/questions/7821518/matplotlib-save-plot-to-numpy-array) helping? – ImportanceOfBeingErnest Aug 23 '17 at 23:09
  • Indeed it was, however, now I'm having problems converting said string with `imdecode(frame,IMREAD_COLOR)` not returning anything at all. I could start a new question to show you. – ThisGuyCantEven Aug 23 '17 at 23:50

0 Answers0