从 Django html 视图获取倒置图像

Getting Inverted image from Django html view

我正在尝试在 Django 上制作基于网络的蛇梯游戏,为此我使用 matplotlibmpld3 在网页上创建和显示我的游戏数据。

我可以在网页上获取我的图像,但它是倒转的。

这段代码哪里出错了?

我的 views.py 文件:

import matplotlib.image as mpimg
import mpld3 as mpld3
import numpy as np
import matplotlib.pyplot as plt

def home(request):
    image =  mpimg.imread('platform3.png')
    figure = plt.figure(dpi=100)
    subplot = figure.add_subplot(111)
    subplot.set_xlim(0, 10)
    subplot.set_ylim(0, 10)
    subplot.imshow(image, extent=[0, 10, 0, 10])
    canvas = FigureCanvas(figure)
    response = django.http.HttpResponse(content_type='image/png')
    canvas.print_png(response)
    html_gen = 'graph.html'
    with open(html_gen, 'w') as f:
        f.write(mpld3.fig_to_html(figure))
        f.write("Hello")

    return render(request, html_gen)

我也应该提供生成的 html_gen.html 文件吗?

只需将 [0, 0] 放在坐标轴的左下角:

subplot.imshow(image, extent=[0, 10, 0, 10], origin='lower')

请看imshow() docs

更新:如何检查和设置默认 image.origin

  1. 检查:

    >>> import matplotlib as mpl
    >>> print(mpl.rcParams['image.origin'])
    upper
    
  2. lower设为默认值(docs):

    $ echo "image.origin : lower" >> .config/matplotlib/matplotlibrc
    
  3. 再次检查:

    >>> import matplotlib as mpl
    >>> print(mpl.rcParams['image.origin'])
    upper