2016/07/14

Make barrel distortion for VR glass

VR app

↑This screenshot looks barrel distortion. This image process seems to be needed for distortion by lens of a VR glass.

distortion by lens

↑Actually a straight line looked a little bit curved through lens of my VR glass, though confusing image.
Anyway this kind of process may be needed for VR app, so I tried this.

I found one web page about correction for lens :
What Is Camera Calibration? - MATLAB & Simulink

There are some equations for the correction, so I applied this to my shader in Metal.
By the way I only implement for only radial distortion, not tangential distortion.

This code below is a part of fragment shader to show texture image. The image receives as ‘tex2D’ and its coordinate does as ‘in.texCoord’.

{
    constexpr sampler quad_sampler;
    half4 texcolor = tex2D.sample(quad_sampler, in.texCoord);
    float4 color = float4(texcolor.r,texcolor.g,texcolor.b, 1.0);
    
    return half4(color);
}
Next code corrects the position of texture and makes distortion.
{
    float k1 = 0.040;
    float k2 = 0.004;
    
    float2 texCoord = in.texCoord;
    float texX = texCoord.x*2.0-1.0;
    float texY = texCoord.y*2.0-1.0;
    float r2 = pow(texX,2.0)+pow(texY,2.0);
    float kk = (1.0 + k1 * r2 + k2* pow(r2,2.0));
    float xx = texX * kk;
    float yy = texY * kk;
    float2 fCoord = float2((xx+1.0)/2.0 , (yy+1.0)/2.0);
    if ( (fCoord.x < 0.0)||(fCoord.x > 1.0)||(fCoord.y < 0.0)||(fCoord.y > 1.0) ) {
        return half4(0,0,0,1.0);
    }
    
    constexpr sampler quad_sampler;
    half4 texcolor = tex2D.sample(quad_sampler, fCoord);
    float4 color = float4(texcolor.r,texcolor.g,texcolor.b, 1.0);
    
    return half4(color);
}
Texture’s coordinate is from 0 to 1. But the center of texture must be (0,0) in transform. So the code changes coordinate and corrects and changes back coordinate again. The edge of image does not get proper values so this code shows just black there. And this does not take k3.

The result is here :

barrel distortion

↑It looks like barrel distortion as expected.

But !
It is really difficult to find the precise k1 and k2 even for my VR glass.
And more, the app user may/must use other VR glass (and their coefficients must be different).
Then this kind of correction may not matter.
Develop | Comments(1) | Trackback(0)
Comment
Comment is pending approval.
Comment is pending blog author's approval.

管理者のみに表示