小编fra*_*xel的帖子

如何将上传的图像传递给Flask中的template.html

我正在使用flask,并尝试使用快速入门教程做一些非常简单的事情,只需在我的机器(本地服务器)上运行.我生成一个简单的上传表单,成功上传图像文件.然后,我想将此图像作为变量传递template.html给页面中的显示.该template.html文件显示细腻,但图像始终是一个broken link image symbol.我尝试了很多不同的路径,但我觉得我做的事情有点不对劲.

import os
from flask import Flask, request, redirect, url_for, send_from_directory, 
                  render_template

UPLOAD_FOLDER = '/home/me/Desktop/projects/flask/uploads'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('uploaded_file', filename=filename))
    return '''
    <!doctype html> …
Run Code Online (Sandbox Code Playgroud)

python flask

22
推荐指数
2
解决办法
3万
查看次数

VTK将窗口图像渲染为numpy数组

在VTK中,我可以使用以下代码段将渲染窗口保存为图像.但是,实际上我想直接将它作为一个numpy数组(没有写然后阅读).

im = vtkWindowToImageFilter()
writer = vtkPNGWriter()
im.SetInput(renderWindow)
im.Update()
writer.SetInputConnection(im.GetOutputPort())
writer.SetFileName("file.png")
writer.Write()
Run Code Online (Sandbox Code Playgroud)

做这个的最好方式是什么?

python numpy vtk

12
推荐指数
1
解决办法
2223
查看次数

通过求和降低阵列的分辨率

如果我有这样的数组:

a = np.array([[ 1, 2, 3, 4],
              [ 5 ,6, 7, 8],
              [ 9,10,11,12],
              [13,14,15,16]])
Run Code Online (Sandbox Code Playgroud)

我想'改变分辨率',最后得到一个更小的数组(比如2行乘2列,或2行乘4列等).我想通过求和来改变这种分辨率.我需要这个来处理大型数组,较小数组的行数,cols将始终是较大数组的一个因素.

将上面的数组减少到2乘2的数组会导致(这就是我想要的):

[[ 14.  22.]
 [ 46.  54.]]
Run Code Online (Sandbox Code Playgroud)

我有这个功能,它做得很好:

import numpy as np

def shrink(data, rows, cols):
    shrunk = np.zeros((rows,cols))
    for i in xrange(0,rows):
        for j in xrange(0,cols):
            row_sp = data.shape[0]/rows
            col_sp = data.shape[1]/cols
            zz = data[i*row_sp : i*row_sp + row_sp, j*col_sp : j*col_sp + col_sp]
            shrunk[i,j] = np.sum(zz)
    return shrunk

print shrink(a,2,2)
print shrink(a,2,1)
#correct output:
[[ 14.  22.]
 [ 46.  54.]]
[[ …
Run Code Online (Sandbox Code Playgroud)

python numpy

11
推荐指数
1
解决办法
3939
查看次数

添加不同尺寸/形状的NumPy矩阵

简而言之:我有两个矩阵(或数组):

import numpy

block_1 = numpy.matrix([[ 0, 0, 0, 0, 0],
                        [ 0, 0, 0, 0, 0],
                        [ 0, 0, 0, 0, 0],
                        [ 0, 0, 0, 0, 0]])

block_2 = numpy.matrix([[ 1, 1, 1],
                        [ 1, 1, 1],
                        [ 1, 1, 1],
                        [ 1, 1, 1]])
Run Code Online (Sandbox Code Playgroud)

block_2block_1元素坐标系中有位移.

pos = (1,1)
Run Code Online (Sandbox Code Playgroud)

我希望能够(快速)添加它们,以获得:

[[0 0 0 0 0]
 [0 1 1 1 0]
 [0 1 1 1 0]
 [0 1 1 1 0]]
Run Code Online (Sandbox Code Playgroud)

总之:我想快速地将两个不同的形状矩阵添加到一起,其中一个矩阵可以移位.得到的矩阵必须具有第一矩阵的形状,并且两个矩阵之间的重叠元素相加.如果没有重叠,则只返回未突变的第一个矩阵.

我有一个工作正常的功能,但它有点难看,并且元素:

def add_blocks(block_1, …
Run Code Online (Sandbox Code Playgroud)

python numpy

9
推荐指数
2
解决办法
9660
查看次数

将dict与其自身进行比较并有效地删除类似的键

我想比较字典中的元素,并根据一些比较标准删除项目.我希望它能有效率.我有一个功能可以做到这一点,但它反复复制字典.当然有一种更好的方式:

mydict = {1:5,2:7,3:9,4:9,7:7,8:0,111:43,110:77}

def partial_duplicate_destroyer(mydict,tolerance):
    for key1 in mydict.keys():
        mydict_copy = mydict.copy()
        for key2 in mydict_copy.keys():
            if key2 - tolerance < key1 < key2 + tolerance and not(key1 == key2):
                del(mydict[key1])
                break
    return mydict

print partial_duplicate_destroyer(mydict,2)
print partial_duplicate_destroyer(mydict,20)
print partial_duplicate_destroyer(mydict,200)

#correct output:
# {4: 9, 8: 0, 111: 43}
# {8: 0, 111: 43}
# {111: 43}
Run Code Online (Sandbox Code Playgroud)

python

9
推荐指数
1
解决办法
188
查看次数

内部引用可防止垃圾回收

我正在编写一个简单的平台游戏,我发现在删除'ghost'实例时,它们会持续存在并且不会被垃圾收集.似乎虽然我删除了所有引用,但ghost对象有一些内部引用,阻止它们被垃圾收集.具体来说,它们具有方法切换的属性.

以下代码说明了我的问题:

import weakref

weak_ghosts = weakref.WeakKeyDictionary()

class Ghost(object):
    def __init__(self):
        #pass
        self.switch = {'eat':self.eat, 'sleep':self.sleep}

    def eat(self):
        pass

    def sleep(self):
        pass

ghost = Ghost()
weak_ghosts[ghost] = None
#ghost.switch = {}    # uncomment this line and ghost is successfully removed
del ghost
print "number of ghosts =", len(weak_ghosts)

#output:
number of ghosts = 1
Run Code Online (Sandbox Code Playgroud)

问题:

  1. 究竟发生了什么?
  2. 我该怎么做才能避免这种情况?
  3. 我是否使用正确的方法制作可切换的方法词典?

python garbage-collection initialization

7
推荐指数
1
解决办法
627
查看次数

在线性时间内在二进制图像中查找特定索引?

我有一个640x480的二进制图像(0s和255s).图像中有一个白色的斑点(接近圆形),我想找到斑点的质心(它总是凸起的).基本上,我们正在处理的是2D布尔矩阵.如果可能的话,我希望运行时线性或更好 - 这可能吗?

到目前为止有两条思路:

  1. 利用这个numpy.where()功能
  2. 对每列和每行中的值求和,然后根据这些数字找出最大值的位置......但有一种快速有效的方法吗?这可能只是我对python相对较新的一个例子.

python boolean numpy image-processing python-imaging-library

4
推荐指数
1
解决办法
986
查看次数

如果列表理解中是if/else/if吗?

我想知道是否可以使用列表推导if/ else不需要导致列表长度与正在处理的列表长度相同?(即没有决赛else)

>>> L = [0, 1, 2, 3, 4, 5, 6]
>>> [v * 10 if v < 3 else v * 2 if v > 3 else v for v in L] #if/else/if/else
[0, 10, 20, 3, 8, 10, 12]
Run Code Online (Sandbox Code Playgroud)

工作良好.但是假设我想省略3,得到:

[0, 10, 20, 8, 10, 12]  # No number 3
Run Code Online (Sandbox Code Playgroud)

我原以为这会起作用:

>>> [v * 10 if v < 3 else v * 2 if v > 3 for v in L] #if/else/if …
Run Code Online (Sandbox Code Playgroud)

python list-comprehension

3
推荐指数
1
解决办法
1万
查看次数

为什么在__init__期间实例化的对象不能看到它们的创建者?

好吧,我也是SO,OOP和python的新手,所以请温柔;)

我在其他地方寻找与此范围问题相关的线索和解释,但没有发现任何问题.如有任何帮助,我将不胜感激.

示例代码:

class Zeus(object):
    def __init__(self):
        self.name='zeus'
        self.maze=Maze()
        self.maze.get_zeus_name_1()
        self.maze.get_zeus_name_2(self)
        self.get_name_1()
        self.get_name_2(self)

    def get_name_1(self):
        try:
            print zeus.name
        except:
            print "impossible!?"

    def get_name_2(self,scope):
        print scope.name

class Maze(object):
    def get_zeus_name_1(self):
        try:
            print zeus.name
        except:
            print "can't be done!?"

    def get_zeus_name_2(self,scope):
        print scope.name

zeus=Zeus()
print 'now external calls:'
zeus.maze.get_zeus_name_1()
zeus.maze.get_zeus_name_2(zeus)
zeus.get_name_1()
zeus.get_name_2(zeus)
Run Code Online (Sandbox Code Playgroud)

输出:

can't be done!?
zeus
impossible!?
zeus
now external calls:
zeus
zeus
zeus
zeus
Run Code Online (Sandbox Code Playgroud)

在实例化期间zeus,如果__init__方法创建另一个类的实例maze,则此新实例无法访问其创建者对象zeus(除非self传递给它).(另外,如果__init__方法在其自己的类中调用方法get_name_1,则该方法也无法访问其对象属性(除非self …

python oop instantiation init

2
推荐指数
1
解决办法
2042
查看次数