如何将二维图片放入三维坐标里显示,我是分三步做的:
1.读取二维图片,获取图片的尺寸
img = Image.open("/Users/yuhao/Desktop/timg.jpg")
x = img.size[0]
y = img.size[1]
2.循环遍历图片的所有像素,将其每一个像素所代表的颜色转换为颜色代码
for i in range(x):
for j in range(y):
r = hex(img.getpixel((i, j))[0])[2:]
b = hex(img.getpixel((i, j))[1])[2:]
g = hex(img.getpixel((i, j))[2])[2:]
if len(r) == 1:
r = '0' + r
if len(b) == 1:
b = '0' + b
if len(g) == 1:
g = '0' + g
col = '#' + r + b + g
3.在循环遍历的同时把二维图片每一个像素点放入三维坐标(需要指定z坐标的位置)
ax.scatter(i, j, 5, c=col, alpha=0.5)
输入数据:
输出数据:
完整代码:
from PIL import Image
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
ax = Axes3D(fig)
img = Image.open("/Users/yuhao/Desktop/timg.jpg")
x = img.size[0]
y = img.size[1]
for i in range(x):
for j in range(y):
r = hex(img.getpixel((i, j))[0])[2:]
b = hex(img.getpixel((i, j))[1])[2:]
g = hex(img.getpixel((i, j))[2])[2:]
if len(r) == 1:
r = '0' + r
if len(b) == 1:
b = '0' + b
if len(g) == 1:
g = '0' + g
col = '#' + r + b + g
# col = '#FF00FF'
ax.scatter(i, j, 5, c=col, alpha=0.5)
plt.show()