python - 我在这个镜头畸变校正程序中不断得到一张白色的照片
问题描述
我想编写一个代码来纠正失真并帮助去除鱼眼图像。我在这里找到了一个伪代码,我试图坚持下去:
http ://www.tannerhelland.com/4743/simple-algorithm-correcting-lens-distortion/
from PIL import Image
import numpy as np
im = Image.open('myimage.png')
img = Image.new("RGB",(512,512),'green')
im = im.convert("RGB")
pix_val = im.load()
pix_valNew = img.load()
width, height = im.size
strength = 1.5
zoom = 1.0
halfWidth = width/2
halfHeight = height/2
theta = -1
if strength == 0:
strength = 0.00001
correctionRadius = ((width**2 + height**2)/strength)**0.5
for x in range(512):
for y in range(512):
newX = x - halfWidth
newY = y - halfHeight
distance = (newX**2 + newY**2)**0.5
r = distance/correctionRadius
if r == 0:
theta = 1
else:
theta = np.arctan(r)/r
sourceX = (int)(halfWidth + theta * newX * zoom)
sourceY = (int)(halfHeight + theta * newY * zoom)
pix_valNew[x,y] = pix_val[sourceX,sourceY]
img.show()
我不断得到一张全白的图像,我无法对其进行故障排除,因为我对它完全陌生。
512x512 是我想要“去鱼”的图像的分辨率。据我了解的逻辑是在鱼眼图像中找到特定像素的位置并将其映射到正常图像中的相应位置
有人要求我提供链接的伪代码,但我也将其粘贴在这里。如下:输入:强度为浮点> = 0。0 =没有变化,高数字等于更强的校正。缩放为浮点 >= 1。(1 = 缩放不变)
算法:
set halfWidth = imageWidth / 2
set halfHeight = imageHeight / 2
if strength = 0 then strength = 0.00001
set correctionRadius = squareroot(imageWidth ^ 2 + imageHeight ^ 2) / strength
for each pixel (x,y) in destinationImage
set newX = x - halfWidth
set newY = y - halfHeight
set distance = squareroot(newX ^ 2 + newY ^ 2)
set r = distance / correctionRadius
if r = 0 then
set theta = 1
else
set theta = arctangent(r) / r
set sourceX = halfWidth + theta * newX * zoom
set sourceY = halfHeight + theta * newY * zoom
set color of pixel (x, y) to color of source image pixel at (sourceX, sourceY)
任何形式的帮助将不胜感激。
解决方案
似乎在某些输入组合下,正在计算源图像的非法索引。一个简单的解决方法是更换
pix_valNew[x,y] = pix_val[sourceX,sourceY]
和:
try:
pix_valNew[x,y] = pix_val[sourceX,sourceY]
except IndexError:
print('IndexError', x, y, sourceX, sourceY)
pix_valNew[x, y] = (0, 0, 0)
另外,刚刚注意到您的代码行:
correctionRadius = ((width**2 + height**2)/strength)**0.5
应该:
correctionRadius = ((width**2 + height**2)**0.5)/strength
推荐阅读
- project-reactor - 如何从通量中取消订阅项目
- html - 粘性页脚重叠正文内容?
- javascript - 如何在javascript中更改滚动时的背景颜色
- c# - 通过点击列表视图中的其他按钮更改按钮的图像,查看单元格
- javascript - winnhttp 资源未加载 - 无法通过表标签名称抓取
- ios - Unmute Video player on volume up button even mute switch is down like Snapchat video player
- webgl - p5.js problem with png alpha in webgl mode
- python - Jupyter notebook : kernel died msg when loading big CSV file
- node.js - Error getting document ReferenceError: from_data is not defined
- c# - WPF dynamically create formula in TextBox