问题遇到的现象和发生背景
从MATLAB迁移代码的时候发现,这一句 :
lastpix = find((rad >= half)&(abs(dist2line)<=linewdt))
不懂在Python中应当如何表示?自己写了一个:
lastpix = np.where((rad >= half) & (abs(dist2line) <= linewdt))
发现好像是不对的,恳请大家指点一二!
MATLAB需要实现的代码,放在下面 function h = motion_PSF(p2,p3)
我自己写的Python代码,也在下面 def motion_PSF(p2,p3):
问题相关代码,请勿粘贴截图
function h = motion_PSF(p2,p3)
len = max(1,p2);
half = (len-1)/2;% rotate half length around center
phi = mod(p3,180)/180*pi;
cosphi = cos(phi);
sinphi = sin(phi);
xsign = sign(cosphi);
linewdt = 1;
% define mesh for the half matrix, eps takes care of the right size
% for 0 & 90 rotation
sx = fix(half*cosphi + linewdt*xsign - len*eps);
sy = fix(half*sinphi + linewdt - len*eps);
[x,y] = meshgrid(0:xsign:sx, 0:sy);
% define shortest distance from a pixel to the rotated line
dist2line = (y*cosphi-x*sinphi);% distance perpendicular to the line
rad = sqrt(x.^2 + y.^2);
% find points beyond the line's end-point but within the line width
lastpix = find((rad >= half)&(abs(dist2line)<=linewdt));
%distance to the line's end-point parallel to the line
x2lastpix = half - abs((x(lastpix) + dist2line(lastpix)*sinphi)/cosphi);
dist2line(lastpix) = sqrt(dist2line(lastpix).^2 + x2lastpix.^2);
dist2line = linewdt + eps - abs(dist2line);
dist2line(dist2line<0) = 0;% zero out anything beyond line width
% unfold half-matrix to the full size
h = rot90(dist2line,2);
h(end+(1:end)-1,end+(1:end)-1) = dist2line;
h = h./(sum(h(:)) + eps*len*len);
if cosphi>0
h = flipud(h);
end
我的解答思路和尝试过的方法
def motion_PSF(p2,p3):
len = max(1,p2)
half = (len-1)/2 #rotate half length around center
phi = np.mod(p3, 180) / 180 * np.pi
cosphi = np.cos(phi)
sinphi = np.sin(phi)
xsign = np.sign(cosphi)
linewdt = 1
# define mesh for the half matrix, eps takes care of the right size
# for 0 & 90 rotation
sx = np.fix(half * cosphi + linewdt * xsign - len * np.spacing(1))
sy = np.fix(half * sinphi + linewdt - len * np.spacing(1))
sxx = np.linspace(0, sx, int(np.ceil(sx / xsign)))
syy = np.linspace(0, sy, int(sy+1))
[x,y] = np.meshgrid(sxx,syy)
# define shortest distance from a pixel to the rotated line
dist2line = (y * cosphi - x * sinphi) #distance perpendicular to the line
rad = np.sqrt(x*x+y*y)
# find points beyond the line's end-point but within the line width
lastpix = np.where((rad >= half) & (abs(dist2line) <= linewdt))
lastpix = np.array(lastpix)
x2lastpix = half - abs((x[lastpix] + dist2line[lastpix]*sinphi)/cosphi)