Bilinear interpolation: Difference between revisions

m
→‎{{header|Wren}}: ImageData.loadFromFile now deprecated, changed to ImageData.load
(added Perl 6)
m (→‎{{header|Wren}}: ImageData.loadFromFile now deprecated, changed to ImageData.load)
 
(27 intermediate revisions by 13 users not shown)
Line 3:
[[wp:Bilinear interpolation|Bilinear interpolation]] is linear interpolation in 2 dimensions, and is typically used for image scaling and for 2D finite element analysis.
 
;Task:
 
;Task:
Open an image file, enlarge it by 60% using bilinear interpolation, then either display the result or save the result to a file.
<br><br>
=={{header|Action!}}==
In the following solution the input file [https://gitlab.com/amarok8bit/action-rosetta-code/-/blob/master/source/lena30g.PPM lena30g.PPM] is loaded from H6 drive. Altirra emulator automatically converts CR/LF character from ASCII into 155 character in ATASCII charset used by Atari 8-bit computer when one from H6-H10 hard drive under DOS 2.5 is used.
{{libheader|Action! Bitmap tools}}
{{libheader|Action! Tool Kit}}
{{libheader|Action! Real Math}}
<syntaxhighlight lang="action!">INCLUDE "H6:REALMATH.ACT"
INCLUDE "H6:LOADPPM5.ACT"
 
PROC PutBigPixel(INT x,y BYTE col)
IF x>=0 AND x<=79 AND y>=0 AND y<=47 THEN
y==LSH 2
col==RSH 4
IF col<0 THEN col=0
ELSEIF col>15 THEN col=15 FI
Color=col
Plot(x,y)
DrawTo(x,y+3)
FI
RETURN
 
PROC DrawImage(GrayImage POINTER image INT x,y)
INT i,j
BYTE c
 
FOR j=0 TO image.gh-1
DO
FOR i=0 TO image.gw-1
DO
c=GetGrayPixel(image,i,j)
PutBigPixel(x+i,y+j,c)
OD
OD
RETURN
 
PROC Lerp(REAL POINTER s,e,t,res)
REAL tmp1,tmp2
 
RealSub(e,s,tmp1) ;tmp1=e-s
RealMult(tmp1,t,tmp2) ;tmp2=(e-s)*t
RealAdd(s,tmp2,res) ;res=s+(e-s)*t
RETURN
 
PROC BilinearInterpolation(GrayImage POINTER src,dst)
INT i,j,x,y,c
REAL mx,my,rx,ry,fx,fy,tmp1,tmp2,tmp3,r00,r01,r10,r11
BYTE c00,c01,c10,c11
 
IntToReal(src.gw-1,tmp1) ;tmp1=src.width-1
IntToReal(dst.gw,tmp2) ;tmp2=dst.width
RealDiv(tmp1,tmp2,mx) ;mx=(src.width-1)/dst.width
IntToReal(src.gh-1,tmp1) ;tmp1=src.height-1
IntToReal(dst.gh,tmp2) ;tmp2=dst.height
RealDiv(tmp1,tmp2,my) ;my=(src.height-1)/dst.height
FOR j=0 TO dst.gh-1
DO
IntToReal(j,tmp1) ;tmp=j
RealMult(tmp1,my,ry) ;ry=j*my
y=Floor(ry)
IntToReal(y,tmp1) ;tmp1=floor(ry)
RealSub(ry,tmp1,fy) ;fy=frac(ry)
FOR i=0 TO dst.gw-1
DO
IntToReal(i,tmp1) ;tmp=i
RealMult(tmp1,mx,rx) ;rx=i*mx
x=Floor(rx)
IntToReal(x,tmp1) ;tmp1=floor(rx)
RealSub(rx,tmp1,fx) ;fx=frac(rx)
 
c00=GetGrayPixel(src,x,y)
c01=GetGrayPixel(src,x,y+1)
c10=GetGrayPixel(src,x+1,y)
c11=GetGrayPixel(src,x+1,y+1)
 
IntToReal(c00,r00)
IntToReal(c01,r01)
IntToReal(c10,r10)
IntToReal(c11,r11)
 
Lerp(r00,r10,fx,tmp1)
Lerp(r01,r11,fx,tmp2)
Lerp(tmp1,tmp2,fy,tmp3)
c=RealToInt(tmp3)
IF c<0 THEN
c=0
ELSEIF c>255 THEN
c=255
FI
SetGrayPixel(dst,i,j,c)
OD
OD
RETURN
 
PROC Main()
BYTE CH=$02FC ;Internal hardware value for last key pressed
BYTE ARRAY data30x30(900),data48x48(2304)
GrayImage im30x30,im48x48
 
Put(125) PutE() ;clear the screen
MathInit()
InitGrayImage(im30x30,30,30,data30x30)
InitGrayImage(im48x48,48,48,data48x48)
PrintE("Loading source image...")
LoadPPM5(im30x30,"H6:LENA30G.PPM")
PrintE("Bilinear interpolation...")
BilinearInterpolation(im30x30,im48x48)
 
Graphics(9)
DrawImage(im30x30,0,0)
DrawImage(im48x48,32,0)
 
DO UNTIL CH#$FF OD
CH=$FF
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Bilinear_interpolation.png Screenshot from Atari 8-bit computer]
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdint.h>
typedef struct {
uint32_t *pixels;
Line 19 ⟶ 134:
return image->pixels[(y*image->w)+x];
}
 
float max(float a, float b) { return (a < b) ? a : b; };
float lerp(float s, float e, float t){return s+(e-s)*t;}
float blerp(float c00, float c10, float c01, float c11, float tx, float ty){
Line 34 ⟶ 151:
x = 0; y++;
}
//float gx = x / (float)(newWidth) * (src->w - 1);
//float gy = y / (float)(newHeight) * (src->h - 1);
// Image should be clamped at the edges and not scaled.
float gx = max(x / (float)(newWidth) * (src->w) - 0.5f, src->w - 1);
float gy = max(y / (float)(newHeight) * (src->h) - 0.5, src->h - 1);
int gxi = (int)gx;
int gyi = (int)gy;
Line 50 ⟶ 170:
putpixel(dst,x, y, result);
}
}</langsyntaxhighlight>
=={{header|C sharp|C#}}==
 
=={{header|C#|C sharp}}==
{{trans|Java}}
Seems to have some artifacting in the output, but the image is at least recognizable.
<langsyntaxhighlight lang="csharp">using System;
using System.Drawing;
 
Line 85 ⟶ 204:
 
int red = (int)Blerp(c00.R, c10.R, c01.R, c11.R, gx - gxi, gy - gyi);
int green = (int)Blerp(c00.G, c10.G, c01.G, c11.RG, gx - gxi, gy - gyi);
int blue = (int)Blerp(c00.B, c10.B, c01.B, c11.RB, gx - gxi, gy - gyi);
Color rgb = Color.FromArgb(red, green, blue);
newImage.SetPixel(x, y, rgb);
Line 105 ⟶ 224:
}
}
}</langsyntaxhighlight>
 
=={{header|D}}==
This uses the module from the Grayscale Image task.
{{trans|C}}
<langsyntaxhighlight lang="d">import grayscale_image;
 
/// Currently this accepts only a Grayscale image, for simplicity.
Line 158 ⟶ 276:
im.rescaleGray(0.3, 0.1).savePGM("lena_smaller.pgm");
im.rescaleGray(1.3, 1.8).savePGM("lena_larger.pgm");
}</langsyntaxhighlight>
=={{header|F sharp|F#}}==
{{trans|C#}}
<syntaxhighlight lang="fsharp">open System
open System.Drawing
 
let lerp (s:float) (e:float) (t:float) =
s + (e - s) * t
 
let blerp c00 c10 c01 c11 tx ty =
lerp (lerp c00 c10 tx) (lerp c01 c11 tx) ty
 
let scale (self:Bitmap) (scaleX:float) (scaleY:float) =
let newWidth = int ((float self.Width) * scaleX)
let newHeight = int ((float self.Height) * scaleY)
let newImage = new Bitmap(newWidth, newHeight, self.PixelFormat)
for x in 0..newWidth-1 do
for y in 0..newHeight-1 do
let gx = (float x) / (float newWidth) * (float (self.Width - 1))
let gy = (float y) / (float newHeight) * (float (self.Height - 1))
let gxi = int gx
let gyi = int gy
let c00 = self.GetPixel(gxi, gyi)
let c10 = self.GetPixel(gxi + 1, gyi)
let c01 = self.GetPixel(gxi, gyi + 1)
let c11 = self.GetPixel(gxi + 1, gyi + 1)
let red = int (blerp (float c00.R) (float c10.R) (float c01.R) (float c11.R) (gx - (float gxi)) (gy - (float gyi)))
let green = int (blerp (float c00.G) (float c10.G) (float c01.G) (float c11.G) (gx - (float gxi)) (gy - (float gyi)))
let blue = int (blerp (float c00.B) (float c10.B) (float c01.B) (float c11.B) (gx - (float gxi)) (gy - (float gyi)))
let rgb = Color.FromArgb(red, green, blue)
newImage.SetPixel(x, y, rgb)
newImage
 
// Taken from https://stackoverflow.com/a/2362114
let castAs<'T when 'T : null> (o:obj) =
match o with
| :? 'T as res -> res
| _ -> Unchecked.defaultof<'T>
 
[<EntryPoint>]
let main _ =
let newImage = Image.FromFile("Lenna100.jpg")
let oi = castAs<Bitmap>(newImage)
if oi = null then
Console.WriteLine("Could not open the source file.")
else
let result = scale oi 1.6 1.6
result.Save("Lenna100_larger.jpg")
 
0 // return an integer exit code</syntaxhighlight>
=={{header|Go}}==
{{trans|C}}
Line 165 ⟶ 331:
<code>[https://godoc.org/golang.org/x/image/draw#BiLinear draw.BiLinear]</code>
from the <code>golang.org/x/image/draw</code> pacakge).
<langsyntaxhighlight Golang="go">package main
 
import (
Line 257 ⟶ 423:
}
return err
}</langsyntaxhighlight>
 
=={{header|J}}==
<syntaxhighlight lang="j">
<lang J>
Note 'FEA'
Here we develop a general method to generate isoparametric interpolants.
Line 322 ⟶ 487:
shape_functions =: COEFFICIENTS mp~ shape_function
interpolate =: mp shape_functions
</syntaxhighlight>
</lang>
<pre>
Note 'demonstrate the interpolant with a saddle'
Line 341 ⟶ 506:
 
Let n mean shape function, C mean constants, i mean interpolant, and the three digits meaning dimensionality, number of corners, and (in base 36) the number of nodes we construct various linear and quadratic interpolants in 1, 2, and 3 dimensions as
<syntaxhighlight lang="j">
<lang J>
Note 'Some elemental information'
 
Line 437 ⟶ 602:
i38q =: mp (C38r mp~ n38r)
i38r =: mp (C38r mp~ n38r)
</syntaxhighlight>
</lang>
 
=={{header|Java}}==
{{trans|Kotlin}}
<langsyntaxhighlight Javalang="java">import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
Line 496 ⟶ 660:
ImageIO.write(image2, "jpg", lenna2);
}
}</langsyntaxhighlight>
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">using Images, FileIO, Interpolations
{{works with|Julia|0.6}}
 
<lang julia>using Images, FileIO, Interpolations
 
function enlarge(A::Matrix, factor::AbstractFloat)
lx, ly = size(A)
nx, ny = round.(Int, factor .* (lx, ly))
vx, vy = linspaceLinRange(1, lx, nx), linspaceLinRange(1, ly, ny)
itp = interpolate(A, BSpline(Linear()), OnGrid())
return itp[(vx, vy])
end
 
A = load("data/lenna100.jpg") |> Matrix{RGB{Float64}};
Alarge = enlarge(A, 1.6);
save("data/lennaenlarged.jpg", Alarge)</lang>
</syntaxhighlight>
 
=={{header|Kotlin}}==
{{trans|C}}
<langsyntaxhighlight lang="scala">// version 1.2.21
 
import java.io.File
Line 566 ⟶ 727:
val lenna2 = File("Lenna100_larger.jpg")
ImageIO.write(image2, "jpg", lenna2)
}</langsyntaxhighlight>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">ImageResize[Import["http://www.rosettacode.org/mw/title.png"], Scaled[1.6], Resampling -> "Linear"]</syntaxhighlight>
{{out}}
Shows a downloaded image that is 60% enlarged.
=={{header|Nim}}==
{{trans|F#}}
{{libheader|imageman}}
<syntaxhighlight lang="nim">import imageman
 
func lerp(s, e, t: float): float =
=={{header|Perl 6}}==
s + (e - s) * t
<lang perl6>#!/usr/bin/env perl6
 
func blerp(c00, c10, c01, c11, tx, ty: float): float =
use v6;
lerp(lerp(c00, c10, tx), lerp(c01, c11, tx), ty)
use GD::Raw;
 
func scale(img: Image; scaleX, scaleY: float): Image =
# Reference:
let newWidth = (img.width.toFloat * scaleX).toInt
# https://github.com/dagurval/perl6-gd-raw
let newHeight = (img.height.toFloat * scaleY).toInt
result = initImage[ColorRGBU](newWidth, newHeight)
for x in 0..<newWidth:
for y in 0..<newHeight:
let gx = x * (img.width - 1) / newWidth
let gy = y * (img.height - 1) / newHeight
let gxi = gx.int
let gyi = gy.int
let gxf = gx - float(gxi)
let gyf = gy - float(gyi)
let c00 = img[gxi, gyi]
let c10 = img[gxi + 1, gyi]
let c01 = img[gxi, gyi + 1]
let c11 = img[gxi + 1, gyi + 1]
let red = blerp(float(c00[0]), float(c10[0]), float(c01[0]), float(c11[0]), gxf, gyf).toInt
let green = blerp(float(c00[1]), float(c10[1]), float(c01[1]), float(c11[1]), gxf, gyf).toInt
let blue = blerp(float(c00[2]), float(c10[2]), float(c01[2]), float(c11[2]), gxf, gyf).toInt
result[x, y] = ColorRGBU([byte(red), byte(green), byte(blue)])
 
when isMainModule:
my $fh1 = fopen('./Lenna100.jpg', "rb") or die;
my $img1 = gdImageCreateFromJpeg($fh1);
 
my $fh2 let image = fopenloadImage[ColorRGBU]('./"Lenna100-larger.jpg',"wb") or die;
let newImage = image.scale(1.6, 1.6)
newImage.saveJPEG("Lenna100_bilinear.jpg")</syntaxhighlight>
=={{header|Perl}}==
<syntaxhighlight lang="perl">use strict;
use warnings;
 
use GD;
my $img1X = gdImageSX($img1);
my $img1Y = gdImageSY($img1);
 
my $image = GD::Image->newFromPng('color_wheel.png');
my $NewX = $img1X * 1.6;
$image->interpolationMethod( ['GD_BILINEAR_FIXED'] );
my $NewY = $img1Y * 1.6;
my($width,$height) = $image->getBounds();
my $image2 = $image->copyScaleInterpolated( 1.6*$width, 1.6*$height );
 
$image2->_file('color_wheel_interpolated.png');</syntaxhighlight>
gdImageSetInterpolationMethod($img1, +GD_BILINEAR_FIXED);
Compare offsite images: [https://github.com/SqrtNegInf/Rosettacode-Perl5-Smoke/blob/master/ref/color_wheel.png color_wheel.png] vs.
[https://github.com/SqrtNegInf/Rosettacode-Perl5-Smoke/blob/master/ref/color_wheel_interpolated.png color_wheel_interpolated.png]
=={{header|Phix}}==
{{libheader|Phix/pGUI}}
Gui app with slider for between 2 and 200% scaling. Various bits of this code scavenged from C#/Go/Kotlin/Wikipedia.
<syntaxhighlight lang="phix">-- demo\rosetta\Bilinear_interpolation.exw
include pGUI.e
 
function interpolate(atom s, e, f)
my $img2 = gdImageScale($img1, $NewX.ceiling, $NewY.ceiling);
--
-- s,e are the start and end values (one original pixel apart),
-- f is a fraction of some point between them, 0(==s)..1(==e).
-- eg s=91 (f=0.2) e=101, we want 0.8 of the 91 + 0.2 of 101,
-- aka if f is 4 times closer to s than e, we want 4 times as
-- much of s as we want of e, with sum(fractions_taken)==1.
--
return s + (e-s)*f -- aka s*(1-f) + e*f
end function
 
function bilinear(integer c00, c10, c01, c11, atom fx, fy)
gdImageJpeg($img2,$fh2,-1);
--
-- for some output pixel, we have calculated the exact point
-- on the original, and extracted the four pixels surrounding
-- that, with fx,fy as the fractional x,y part of the 1x1 box.
-- Like a capital H, we want some fraction on the left and the
-- same on the right, then some fraction along the horizontal.
-- It would be equivalent to do top/bottom then the vertical,
-- which is handy since I am no longer certain which of those
-- the following actually does, especially since we got the
-- pixels from original[y,x] rather than original[x,y], and
-- imImage and IupImage have {0,0} in different corners - but
-- the output looks pretty good, and I think you would easily
-- notice were this even slightly wrong, and in fact an early
-- accidental typo of r10/r01 indeed proved very evident.
--
atom left = interpolate(c00,c10,fx),
right = interpolate(c01,c11,fx)
return floor(interpolate(left,right,fy))
end function
 
function scale_image(imImage img, atom scaleX, scaleY)
gdImageDestroy($img1);
integer width = im_width(img),
gdImageDestroy($img2);
height = im_height(img),
new_width = floor(width * scaleX)-1,
new_height = floor(height * scaleY)-1
atom mx = (width-1)/new_width,
my = (height-1)/new_height
sequence original = repeat(repeat(0,width),height)
sequence new_image = repeat(repeat(0,new_width),new_height)
 
-- Extract the original pixels from the image [about
fclose($fh1);
-- twice as fast as 4*im_pixel() in the main loop.]
fclose($fh2);
for y=height-1 to 0 by -1 do
</lang>
for x=0 to width-1 do
original[height-y,x+1] = im_pixel(img, x, y)
end for
end for
 
for x=0 to new_width-1 do
{{out}}
for y=0 to new_height-1 do
<pre>file Lenna100*
atom ax = x*mx, -- map onto original
Lenna100.jpg: JPEG image data, JFIF standard 1.01, resolution (DPI), density 72x72, segment length 16, baseline, precision 8, 512x512, frames 3
ay = y*my
Lenna100-larger.jpg: JPEG image data, JFIF standard 1.01, resolution (DPI), density 96x96, segment length 16, comment: "CREATOR: gd-jpeg v1.0 (using IJG JPEG v80), default quality", baseline, precision 8, 820x820, frames 3</pre>
integer ix = floor(ax), -- top left
iy = floor(ay)
ax -= ix -- fraction of the 1x1 box
ay -= iy
integer {r00,g00,b00} = original[iy+1,ix+1],
{r10,g10,b10} = original[iy+1,ix+2],
{r01,g01,b01} = original[iy+2,ix+1],
{r11,g11,b11} = original[iy+2,ix+2],
r = bilinear(r00,r10,r01,r11,ax,ay),
g = bilinear(g00,g10,g01,g11,ax,ay),
b = bilinear(b00,b10,b01,b11,ax,ay)
new_image[y+1,x+1] = {r,g,b}
end for
end for
new_image = flatten(new_image) -- (as needed by IupImageRGB)
Ihandle new_img = IupImageRGB(new_width, new_height, new_image)
return new_img
end function
 
IupOpen()
 
constant w = machine_word()
atom pError = allocate(w)
imImage im1 = imFileImageLoadBitmap("Lena.ppm",0,pError)
if im1=NULL then
?{"error opening image",peekNS(pError,w,1)}
{} = wait_key()
abort(0)
end if
 
Ihandle dlg,
scale = IupValuator(NULL,"MIN=2,MAX=200,VALUE=160"),
redraw = IupButton("redraw (160%)")
 
Ihandln image1 = IupImageFromImImage(im1),
image2 = scale_image(im1,1.6,1.6),
label1 = IupLabel(),
label2 = IupLabel()
IupSetAttributeHandle(label1, "IMAGE", image1)
IupSetAttributeHandle(label2, "IMAGE", image2)
 
function valuechanged_cb(Ihandle /*scale*/)
atom v = IupGetDouble(scale,"VALUE")
IupSetStrAttribute(redraw,"TITLE","redraw (%d%%)",{v})
return IUP_DEFAULT
end function
IupSetCallback(scale,"VALUECHANGED_CB",Icallback("valuechanged_cb"))
 
function redraw_cb(Ihandle /*redraw*/)
IupSetAttributeHandle(label2, "IMAGE", NULL)
image2 = IupDestroy(image2)
atom v = IupGetDouble(scale,"VALUE")/100
image2 = scale_image(im1,v,v)
IupSetAttributeHandle(label2, "IMAGE", image2)
IupSetAttribute(dlg,"SIZE",NULL)
IupRefresh(dlg)
return IUP_DEFAULT
end function
IupSetCallback(redraw,"ACTION",Icallback("redraw_cb"))
 
dlg = IupDialog(IupVbox({IupHbox({scale, redraw}),
IupHbox({label1, label2})}))
IupSetAttribute(dlg, "TITLE", "Bilinear interpolation")
IupShow(dlg)
 
IupMainLoop()
IupClose()</syntaxhighlight>
=={{header|Python}}==
 
Of course, it is much faster to use PIL, Pillow or SciPy to resize an image than to rely on this code.
 
<langsyntaxhighlight lang="python">#!/bin/python
import numpy as np
from scipy.misc import imread, imshow
Line 656 ⟶ 960:
 
imshow(enlargedImg)
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
This mimics the Wikipedia example.
<langsyntaxhighlight lang="racket">#lang racket
(require images/flomap)
 
Line 681 ⟶ 984:
(λ (k x y)
(flomap-bilinear-ref
fm k (+ 1/2 (/ x 250)) (+ 1/2 (/ y 250))))))</langsyntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>#!/usr/bin/env perl6
 
use v6;
use GD::Raw;
 
# Reference:
# https://github.com/dagurval/perl6-gd-raw
 
my $fh1 = fopen('./Lenna100.jpg', "rb") or die;
my $img1 = gdImageCreateFromJpeg($fh1);
 
my $fh2 = fopen('./Lenna100-larger.jpg',"wb") or die;
 
my $img1X = gdImageSX($img1);
my $img1Y = gdImageSY($img1);
 
my $NewX = $img1X * 1.6;
my $NewY = $img1Y * 1.6;
 
gdImageSetInterpolationMethod($img1, +GD_BILINEAR_FIXED);
 
my $img2 = gdImageScale($img1, $NewX.ceiling, $NewY.ceiling);
 
gdImageJpeg($img2,$fh2,-1);
 
gdImageDestroy($img1);
gdImageDestroy($img2);
 
fclose($fh1);
fclose($fh2);
</syntaxhighlight>
 
{{out}}
<pre>file Lenna100*
Lenna100.jpg: JPEG image data, JFIF standard 1.01, resolution (DPI), density 72x72, segment length 16, baseline, precision 8, 512x512, frames 3
Lenna100-larger.jpg: JPEG image data, JFIF standard 1.01, resolution (DPI), density 96x96, segment length 16, comment: "CREATOR: gd-jpeg v1.0 (using IJG JPEG v80), default quality", baseline, precision 8, 820x820, frames 3</pre>
=={{header|Scala}}==
===Imperative solution===
<langsyntaxhighlight Scalalang="scala">import java.awt.image.BufferedImage
import java.io.{File, IOException}
 
Line 743 ⟶ 1,083:
 
private def lerp(s: Float, e: Float, t: Float) = s + (e - s) * t
}</langsyntaxhighlight>
=={{header|Sidef}}==
{{trans|C}}
<langsyntaxhighlight lang="ruby">require('Imager')
 
func scale(img, scaleX, scaleY) {
Line 786 ⟶ 1,126:
var img = %O<Imager>.new(file => "input.png")
var out = scale(img, 1.6, 1.6)
out.write(file => "output.png")</langsyntaxhighlight>
 
=={{header|Tcl}}==
 
Line 794 ⟶ 1,133:
The script below will show the computed image in a GUI frame, and present a button to save it.
 
<syntaxhighlight lang="tcl">
<lang Tcl>
package require Tk
 
Line 839 ⟶ 1,178:
pack [button .b -text "save" -command [list save $im]]
 
</syntaxhighlight>
</lang>
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<syntaxhighlight lang="vbnet">Imports System.Drawing
 
Module Module1
 
Function Lerp(s As Single, e As Single, t As Single) As Single
Return s + (e - s) * t
End Function
 
Function Blerp(c00 As Single, c10 As Single, c01 As Single, c11 As Single, tx As Single, ty As Single) As Single
Return Lerp(Lerp(c00, c10, tx), Lerp(c01, c11, tx), ty)
End Function
 
Function Scale(self As Bitmap, scaleX As Single, scaleY As Single) As Image
Dim newWidth = CInt(Math.Floor(self.Width * scaleX))
Dim newHeight = CInt(Math.Floor(self.Height * scaleY))
Dim newImage As New Bitmap(newWidth, newHeight, self.PixelFormat)
 
For x = 0 To newWidth - 1
For y = 0 To newHeight - 1
Dim gx = CSng(x) / newWidth * (self.Width - 1)
Dim gy = CSng(y) / newHeight * (self.Height - 1)
Dim gxi = CInt(Math.Floor(gx))
Dim gyi = CInt(Math.Floor(gy))
Dim c00 = self.GetPixel(gxi, gyi)
Dim c10 = self.GetPixel(gxi + 1, gyi)
Dim c01 = self.GetPixel(gxi, gyi + 1)
Dim c11 = self.GetPixel(gxi + 1, gyi + 1)
 
Dim red = CInt(Blerp(c00.R, c10.R, c01.R, c11.R, gx - gxi, gy - gyi))
Dim green = CInt(Blerp(c00.G, c10.G, c01.G, c11.G, gx - gxi, gy - gyi))
Dim blue = CInt(Blerp(c00.B, c10.B, c01.B, c11.B, gx - gxi, gy - gyi))
Dim rgb = Color.FromArgb(red, green, blue)
 
newImage.SetPixel(x, y, rgb)
Next
Next
 
Return newImage
End Function
 
Sub Main()
Dim newImage = Image.FromFile("Lenna100.jpg")
If TypeOf newImage Is Bitmap Then
Dim oi As Bitmap = newImage
Dim result = Scale(oi, 1.6, 1.6)
result.Save("Lenna100_larger.jpg")
Else
Console.WriteLine("Could not open the source file.")
End If
End Sub
 
End Module</syntaxhighlight>
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|DOME}}
Note that currently DOME's ImageData class can only save files to disk in .png format.
<syntaxhighlight lang="wren">import "dome" for Window
import "graphics" for Canvas, Color, ImageData
import "math" for Math
 
/* gets the 'n'th byte of a 4-byte integer */
var GetByte = Fn.new { |i, n| (i >> (n * 8)) & 0xff }
 
var Blerp = Fn.new { |c00, c10, c01, c11, tx, ty|
return Math.lerp(Math.lerp(c00, tx, c10), ty, Math.lerp(c01, tx, c11))
}
 
var ColorToInt = Fn.new { |c| (c.r) + (c.g << 8) + (c.b << 16) + (c.a << 24) }
 
class BilinearInterpolation {
construct new(filename, filename2, scaleX, scaleY) {
Window.title = "Bilinear interpolation"
_img = ImageData.load(filename)
var newWidth = (_img.width * scaleX).floor
var newHeight = (_img.height * scaleY).floor
Window.resize(newWidth, newHeight)
Canvas.resize(newWidth, newHeight)
_img2 = ImageData.create(filename2, newWidth, newHeight)
_filename2 = filename2
}
 
init() {
scaleImage()
}
 
scaleImage() {
for (x in 0..._img2.width) {
for (y in 0..._img2.height) {
var gx = x / _img2.width * (_img.width - 1)
var gy = y / _img2.height * (_img.height - 1)
var gxi = gx.floor
var gyi = gy.floor
var rgb = 0
var c00 = _img.pget(gxi, gyi)
var c10 = _img.pget(gxi+1, gyi)
var c01 = _img.pget(gxi, gyi+1)
var c11 = _img.pget(gxi+1, gyi+1)
for (i in 0..3) {
var b00 = GetByte.call(ColorToInt.call(c00), i)
var b10 = GetByte.call(ColorToInt.call(c10), i)
var b01 = GetByte.call(ColorToInt.call(c01), i)
var b11 = GetByte.call(ColorToInt.call(c11), i)
var ble = Blerp.call(b00, b10, b01, b11, gx-gxi, gy-gyi).floor << (8 * i)
rgb = rgb | ble
}
var r = GetByte.call(rgb, 0)
var g = GetByte.call(rgb, 1)
var b = GetByte.call(rgb, 2)
var a = GetByte.call(rgb, 3)
_img2.pset(x, y, Color.rgb(r, g, b, a))
}
}
_img2.draw(0, 0)
_img2.saveToFile(_filename2)
}
 
update() {}
 
draw(alpha) {}
}
 
var Game = BilinearInterpolation.new("Lenna100.jpg", "Lenna100_larger.png", 1.6, 1.6)</syntaxhighlight>
 
=={{header|Yabasic}}==
{{trans|Nim}}
<syntaxhighlight lang="yabasic">// Rosetta Code problem: http://rosettacode.org/wiki/Bilinear_interpolation
// Adapted from Nim to Yabasic by Galileo, 01/2022
 
import ReadFromPPM2
 
sub lerp(s, e, t)
return s + (e - s) * t
end sub
sub blerp(c00, c10, c01, c11, tx, ty)
return lerp(lerp(c00, c10, tx), lerp(c01, c11, tx), ty)
end sub
sub scale(scaleX, scaleY)
local width, height, x, y, gx, gy, gxi, gyi, gxf, gyf, c00$, c10$, c01$, c11$
width = peek("winwidth")
height = peek("winheight")
let newWidth = int(width * scaleX)
let newHeight = int(height * scaleY)
dim result(newWidth, newHeight, 3)
for x = 1 to newWidth
for y = 1 to newHeight:
let gx = x * (width - 1) / newWidth
let gy = y * (height - 1) / newHeight
let gxi = int(gx)
let gyi = int(gy)
let gxf = gx - gxi
let gyf = gy - gyi
let c00$ = right$(getbit$(gxi, gyi, gxi, gyi), 6)
let c10$ = right$(getbit$(gxi + 1, gyi, gxi + 1, gyi), 6)
let c01$ = right$(getbit$(gxi, gyi + 1, gxi, gyi + 1), 6)
let c11$ = right$(getbit$(gxi + 1, gyi + 1, gxi + 1, gyi + 1), 6)
result(x, y, 1) = int(blerp(dec(left$(c00$, 2)), dec(left$(c10$, 2)), dec(left$(c01$, 2)), dec(left$(c11$, 2)), gxf, gyf))
result(x, y, 2) = int(blerp(dec(mid$(c00$, 3, 2)), dec(mid$(c10$, 3, 2)), dec(mid$(c01$, 3, 2)), dec(mid$(c11$, 3, 2)), gxf, gyf))
result(x, y, 3) = int(blerp(dec(right$(c00$, 2)), dec(right$(c10$, 2)), dec(right$(c01$, 2)), dec(right$(c11$, 2)), gxf, gyf))
next
next
end sub
readPPM("lena.ppm")
print "Be patient, please ..."
scale(1.6, 1.6)
close window
open window newWidth, newHeight
for x = 1 to newWidth
for y = 1 to newHeight
color result(x, y, 1), result(x, y, 2), result(x, y, 3)
dot x, y
next
next</syntaxhighlight>
=={{header|zkl}}==
{{trans|C}}
Line 845 ⟶ 1,363:
 
Not fast enough to be called slow.
<langsyntaxhighlight lang="zkl">fcn lerp(s,e,t){ s + (e-s)*t; }
fcn blerp(c00,c10,c01,c11, tx,ty){ lerp(lerp(c00,c10,tx), lerp(c01,c11,tx),ty) }
fcn scale(src, scaleX,scaleY){
Line 865 ⟶ 1,383:
}
dst
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">img:=PPM.readPPMFile("lena.ppm");
img2:=scale(img,1.5,1.5);
img2.write(File("lena1.5.ppm","wb"));
scale(img,0.5,0.5).write(File("lena.5.ppm","wb"));</langsyntaxhighlight>
{{out}}
http://www.zenkinetic.com/Images/RosettaCode/3Lenas.jpg
9,476

edits