jbs*_*ssm 5 python image matplotlib figure
我正在尝试将 Python 生成的图像与文件中的图像/照片进行比较。
到目前为止,最好的方法是在 Matplotlib 中生成一个图形,然后将其转换为 numpy 数组,并将这些值与我从图像中获得的值进行比较。
我得到了以下代码,将 Matplotlib 图转换为具有 RGB 通道的 3D numpy 数组:
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
Run Code Online (Sandbox Code Playgroud)
问题之一 - 到目前为止我试图解决的问题 - 是这个转换后的图像没有被裁剪。例如,如果我画一个占据整个画布的正方形,Matplotlib 会将这个烦人的框架放在周围,然后将其转换并混合我的所有结果。
如何仅获取我制作的图形的数值(没有任何框架或轴)?
或者更好的是,如果有一种我不知道的更简单的方法来比较 NumPy/Matplotlib 中的图形和图像,请告诉我。
好吧,这并不是使用 Matplotlib 来解决当前问题的真正答案,但我为了这项工作放弃了这个库,只使用了 PIL。
这很简单,尽管它也很慢(但我不知道它是否比 Matplotlib 慢)。
代码如下:
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
Run Code Online (Sandbox Code Playgroud)
如果您知道加快此过程的方法,请告诉我。
| 归档时间: |
|
| 查看次数: |
2157 次 |
| 最近记录: |