问题描述
在第234页的Introduction to Applied Linear Algebra – Vectors,Matrices,and Least Squares
中,有一个示例将解决最小二乘问题,以找到导致所有625个像素照度为1的灯功率。
当我尝试复制下一页中显示的图时,所有灯光的像素强度显示如下:
我无法获得如上所示的结果。
但是,由于各个灯而产生的各个像素强度可以像这样容易地可视化
[
当我尝试可视化所有灯泡时,问题就来了。
如果我尝试添加灯的各个像素值,那么我会得到这样的图片
这与书中所显示的完全不同。我必须以某种方式混合单个图像,而不会降低由暗像素引起的强度。如果有人可以给我一些如何将所有图像融合为一体的想法,我将不胜感激。
如果有人感兴趣,可以在下面找到代码
代码
import numpy as np
from mpl_toolkits.axes_grid1 import ImageGrid
# number of lamps
n = 10
# x,y positions of lamps and height above floor
lamps = np.array([[4.1,20.4,4],[14.1,21.3,3.5],[22.6,17.1,6],[5.5,12.3,4.0],[12.2,9.7,[15.3,13.8,[21.3,10.5,5.5],[3.9,3.3,5.0],[13.1,4.3,[20.3,4.2,4.5]])
N = 25 # grid size
m = N*N # number of pixels
# construct m x 2 matrix with coordinates of pixel centers
pixels = np.hstack([np.outer(np.arange(0.5,N,1),np.ones(N)).reshape(m,np.outer(np.ones(N),np.arange(0.5,1)).reshape(m,1)])
# The m x n matrix A maps lamp powers to pixel intensities.
# A[i,j] is inversely proportional to the squared distance of
# lamp j to pixel i.
A = np.zeros((m,n))
for i in range(m):
for j in range(n):
A[i,j] = 1.0 / (np.linalg.norm(np.hstack([pixels[i,:],0])- lamps[j,:])**2)
A = (m/np.sum(A)) * A # scale elements of A
# Plot the intensities of each pixel as a grid
# TODO Figure out a way to blend these images.
allLamps = A[:,0].reshape(N,N)
for i in range(1,n):
lampI = A[:,i].reshape(N,N)
allLamps += lampI
fig = plt.figure(figsize=(4.,4.))
plt.imshow(lampI)
plt.scatter(lamps[i,1],lamps[i,0])
# Visualize the intensity of all the lamps in single image
fig = plt.figure(figsize=(4.,4.))
plt.imshow(allLamps)
plt.scatter(lamps[:,lamps[:,0])
# Solve the least squares problem
lampPowers = np.linalg.lstsq(A,np.ones(m))
print("Optimal lamp powers to have 1 value for every pixel is = \n",lampPowers[0])
解决方法
我猜这本书的结果有点夸张。但这实际上很简单。
假设所有的灯泡功率都设置为最高,则只需将矩阵A
与灯泡功率阵列相乘,我们就得到了第一张房间照明不佳的图片。
然后,在解决最小二乘问题后,需要将相同的矩阵乘以我们获得的灯功率阵列,以可视化最佳照明的房间。
代码
lResultIn1 = np.matmul(A,np.ones(n))
fig = plt.figure(figsize=(4.,4.))
plt.imshow(lResultIn1.reshape(25,25))
plt.scatter(lamps[:,1],lamps[:,0])
# Solve the least squares problem
lampPowers = np.linalg.lstsq(A,np.ones(m))
# Plot the optimally lit room
lResultOptimal = A @ np.asarray(lampPowers[0])
fig = plt.figure(figsize=(4.,4.))
plt.imshow(lResultOptimal.reshape(25,0])
我们从最小二乘问题中得到的解决方案是最大照明区域的每个灯功率。
解决方案
Optimal lamp powers to have 1 value for every pixel is =
[ 1.46211018 0.78797433 2.96641047 0.74358042 0.08317333 0.21263945
0.21218408 2.05114815 0.90760315 1.47222464]
我们得到了两个不同的情节,例如
将所有电源设置为一个的房间点亮
您可以清楚地看到,边缘的灯明亮地点亮,从而最大程度地散布了整个房间。
希望我在以正确的方式思考。如果我错了,请纠正我。