Convert Matplotlib shape to a NumPy array without borders / frame or axis

I am trying to compare a generated image in Python with an image / photograph in a file.

The best way to get this so far is to create a shape in Matplotlib and then convert it to a numpy array and compare the values ​​with the values ​​I get from my image.

I got the following code to convert a Matplotlib shape into a 3D numpy array with RGB channels:

def fig2data ( fig ): """ @brief Convert a Matplotlib figure to a 3D numpy array with RGB channels and return it @param fig a matplotlib figure @return a numpy 3D array of RGB values """ # draw the renderer fig.canvas.draw ( ) # Get the RGBA buffer from the figure w,h = fig.canvas.get_width_height() buf = numpy.fromstring ( fig.canvas.tostring_rgb(), dtype=numpy.uint8 ) buf.shape = ( w, h, 3 ) return buf 

One of the problems - the one that I am trying to understand so far - is that this converted image did not get cropped. For example, if I draw a square filling the entire canvas, Matplotlib places this announcing frame around, and it converts and mixes all my results.

How to get only numerical values ​​- without any frame or axis - the pattern I made?

Or even better, if there is a much simpler way to compare the shape and image in NumPy / Matplotlib that I don’t know about, please let me know.

+4
source share
1 answer

Well, this is not quite the answer to the problem using Matplotlib, but I abandoned this library for this work and just used PIL.

This is pretty easy, albeit pretty slow (but I don't know, slower than Matplotlib).

The code is as follows:

 def makeImage (triangle, largura, altura): """ triangle: receives a tuple in the form: x1, y1, x2, y2, x3, y3, R, G, B, A largura: image weight altura: image height returns: numPy array of the triangle composed final image """ back = Image.new('RGBA', (largura,altura), (0,0,0,0)) poly = Image.new('RGBA', (largura,altura)) pdraw = ImageDraw.Draw(poly) pdraw.polygon([1,2,3,4,5,6], fill=(255,0,0,127)) back.paste(poly,mask=poly) back = back.convert('RGB') backArr = asarray(back) #back.show() return backArr 

If you know a way to expedite this process, please let me know.

0
source

Source: https://habr.com/ru/post/1387972/


All Articles