我有一个大小为 512x256 的二维 numpy 矩阵。我可以使用 PIL 或 scipy 等轻松地将它转换为图像,但显然,这给了我一个大小为 512x256 的矩形形状。我想知道我是否可以做点什么让这个矩阵像附图一样变成圆锥形?
我的想法是,矩阵的第一列将是圆锥体最左侧的线,而矩阵的下一列将稍微靠近该线,依此类推。由于两个极端之间的角度是 45 度,而我有 256 列,这意味着每条线的角度增量为 (45/256) 度?这些只是一些粗略的想法,但如果他们对我应该如何进行此操作有任何想法,我想向社区学习?我正在设想一个黑色方形主图像和它中间的这个圆锥体。有什么想法/想法吗?
最佳答案
这是一个快速但粗略的解决方案,它将结果图像中的极坐标映射到原始图像中的直角坐标,并在原始图像的每个 channel 上使用 interp2d
:
import numpy as np
from scipy import misc
from scipy.interpolate import interp2d
from math import pi, atan2, hypot
inputImagePath = 'wherever/whateverYouWantToInterpolate.jpg'
resultWidth = 800
resultHeight = 600
centerX = resultWidth / 2
centerY = - 50.0
maxAngle = 45.0 / 2 / 180 * pi
minAngle = -maxAngle
minRadius = 100.0
maxRadius = 600.0
inputImage = misc.imread(inputImagePath)
h,w,chn = inputImage.shape
print(f"h = {h} w = {w} chn = {chn}")
channels = [inputImage[:,:,i] for i in range(3)]
interpolated = [interp2d(range(w), range(h), c) for c in channels]
resultImage = np.zeros([resultHeight, resultWidth, 3], dtype = np.uint8)
for c in range(resultWidth):
for r in range(resultHeight):
dx = c - centerX
dy = r - centerY
angle = atan2(dx, dy) # yes, dx, dy in this case!
if angle < maxAngle and angle > minAngle:
origCol = (angle - minAngle) / (maxAngle - minAngle) * w
radius = hypot(dx, dy)
if radius > minRadius and radius < maxRadius:
origRow = (radius - minRadius) / (maxRadius - minRadius) * h
for chn in range(3):
resultImage[r, c, chn] = interpolated[chn](origCol, origRow)
import matplotlib.pyplot as plt
plt.imshow(resultImage)
plt.show()
产生:
性能很糟糕,懒得“矢量化”了。将在了解如何操作时进行更新。
关于python - 二维矩阵到圆锥图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49713201/