本文介绍了Python:来自 2D 图像的 3D 轮廓 - pylab 和 contourf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于 Python(pylab) 和绘图的问题 -我能够加载和显示图像(下面的代码加载下面的图像),但我无法将其绘制为 3D 轮廓,我知道 pylab.contourf(x,y) 需要一个数组,z) 虽然我不确定如何从加载的图像数据中实现这一点.

I have a question regarding Python(pylab) and plotting -I'm able to load and display an image (code below loads the image below), but I'm unable to plot this as a contour in 3D, I understand an array is required for pylab.contourf(x,y,z) though I'm unsure how to achieve this from the loaded image data.

请提供任何建议和帮助.我的代码:

Any suggestions and assistance please. My code:

from PIL import Image
import pylab

fileName = "image1.png"
im = Image.open(fileName)
#pylab.contourf(im) # don't work - needs an array but how
pylab.axis('off')
pylab.imshow(im)
pylab.show()

推荐答案

OK,研究一下简化代码,关键是convert('L'),即rgb转灰度,然后Ali_m的代码就可以了:

OK, some research and simplifying code, the key is convert('L'), i.e. rgb to greyscale, then Ali_m's code works:

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pylab as pl
from PIL import Image
import numpy as np
import pylab

img = Image.open('40.jpg').convert('L')
z   = np.asarray(img)
mydata = z[::1,::1]
fig = pl.figure(facecolor='w')
ax1 = fig.add_subplot(1,2,1)
im = ax1.imshow(mydata,interpolation='nearest',cmap=pl.cm.jet)
ax1.set_title('2D')

ax2 = fig.add_subplot(1,2,2,projection='3d')
x,y = np.mgrid[:mydata.shape[0],:mydata.shape[1]]
ax2.plot_surface(x,y,mydata,cmap=pl.cm.jet,rstride=1,cstride=1,linewidth=0.,antialiased=False)
ax2.set_title('3D')
ax2.set_zlim3d(0,100)
pl.show()

这篇关于Python:来自 2D 图像的 3D 轮廓 - pylab 和 contourf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 16:36