python内存密集型脚本

2024-05-12 22:37:40 发布

您现在位置:Python中文网/ 问答频道 /正文

经过大约4个星期的学习,实验等,我终于有了一个脚本,这是我想要的。它根据我创建的投影矩阵来改变图像的视角。当我为一个图像运行脚本时,它工作得很好,但是我想在一个图形中绘制六个图像。当我尝试这样做时,我得到了一个内存错误。在

所有图像的宽度为2448px,高度为2048px。我的剧本:

files = {'cam1': 'c1.jpg',
         'cam2': 'c2.jpg',
         'cam3': 'c3.jpg',
         'cam4': 'c4.jpg',
         'cam5': 'c5.jpg',
         'cam6': 'c6.jpg'}

fig, ax = plt.subplots()

for camname in files:
    img = Image.open(files[camname])
    gray_img = np.asarray(img.convert("L"))
    img = np.asarray(img)
    height, width, channels = img.shape

    usedP = np.array(P[camname][:,[0,1,3]])
    usedPinv = np.linalg.inv(usedP)
    U, V = np.meshgrid(range(gray_img.shape[1]),
                       range(gray_img.shape[0]))
    UV = np.vstack((U.flatten(),
                    V.flatten())).T
    ones = np.ones((UV.shape[0],1))
    UV = np.hstack((UV, ones))

    # create UV_warped
    UV_warped = usedPinv.dot(UV.T).T

    # normalize vector by dividing by the third column (which should be 1)
    normalize_vector = UV_warped[:,2].T
    UV_warped = UV_warped/normalize_vector[:,None]

    # masks
    # pixels that are above the horizon and where the V-projection is therefor positive (X in argus): make 0, 0, 1
    # pixels that are to far: make 0,0,1
    masks = [UV_warped[:,0]<=0, UV_warped[:,0]>2000, UV_warped[:,1]>5000, UV_warped[:,1]<-5000] # above horizon: => [0,0,1]
    total_mask = masks[0] | masks[1] | masks[2] | masks[3]
    UV_warped[total_mask] = np.array([[0.0, 0.0, 1.0]])

    # show plot
    X_warped = UV_warped[:,0].reshape((height, width))
    Y_warped = UV_warped[:,1].reshape((height, width))
    gray_img = gray_img[:-1, :-1]

    # add colors
    rgb = img[:,:-1,:].reshape((-1,3)) / 255.0 # we have 1 less faces than grid cells
    rgba = np.concatenate((rgb, np.ones((rgb.shape[0],1))), axis=1)

    plotimg = ax.pcolormesh(X_warped, Y_warped, img.mean(-1)[:,:], cmap='Greys')
    plotimg.set_array(None)
    plotimg.set_edgecolor('none')
    plotimg.set_facecolor(rgba)

ax.set_aspect('equal')
plt.show()

我有种感觉numpy.meshgrid是相当的记忆密集型,但我不确定。有人看到我的记忆在哪里迅速消失了吗?(顺便说一句,我有一台内存为12Gb的笔记本电脑,只有很小一部分是由其他程序使用的)


Tags: 图像imgnponesfilesaxuvjpg
3条回答

您可能需要使用this library来分析代码。在

它将显示脚本使用内存的位置。在

我通常使用profilecProfile模块进行评测,因为这使得测试代码的各个部分相当容易。在

Python Profilers

有一个关于内存分析器的Stackoverflow问题here。另外,我在过去曾使用过this answer中的技巧,作为快速了解代码内存在哪里失控的方法。我只是把资源.getrusage()结果到处都是。它不干净,也不总是有效的,但它是标准库的一部分,而且很容易实现。在

相关问题 更多 >