Image convolution: Difference between revisions

m
(link to wikipedia article)
m (→‎{{header|Wren}}: Minor tidy)
 
(2 intermediate revisions by 2 users not shown)
Line 17:
=={{header|Action!}}==
{{libheader|Action! Bitmap tools}}
<langsyntaxhighlight Actionlang="action!">INCLUDE "H6:LOADPPM5.ACT"
 
DEFINE HISTSIZE="256"
Line 109:
DO UNTIL CH#$FF OD
CH=$FF
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Image_convolution.png Screenshot from Atari 8-bit computer]
Line 115:
=={{header|Ada}}==
First we define floating-point stimulus and color pixels which will be then used for filtration:
<langsyntaxhighlight lang="ada">type Float_Luminance is new Float;
 
type Float_Pixel is record
Line 149:
begin
return (To_Luminance (X.R), To_Luminance (X.G), To_Luminance (X.B));
end To_Pixel;</langsyntaxhighlight>
Float_Luminance is an unconstrained equivalent of Luminance. Float_Pixel is one to Pixel. Conversion operations To_Luminance and To_Pixel saturate the corresponding values. The operation + is defined per channels. The operation * is defined as multiplying by a scalar. (I.e. Float_Pixel is a vector space.)
 
Now we are ready to implement the filter. The operation is performed in memory. The access to the image array is minimized using a slid window. The filter is in fact a triplet of filters handling each image channel independently. It can be used with other color models as well.
<langsyntaxhighlight lang="ada">type Kernel_3x3 is array (-1..1, -1..1) of Float_Luminance;
 
procedure Filter (Picture : in out Image; K : Kernel_3x3) is
Line 198:
Above (Picture'Last (2)) := W21;
end loop;
end Filter;</langsyntaxhighlight>
Example of use:
<langsyntaxhighlight lang="ada"> F1, F2 : File_Type;
begin
Open (F1, In_File, "city.ppm");
Line 211:
Put_PPM (F2, X);
end;
Close (F2);</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
Line 217:
[[Image:original_bbc.jpg|right]]
[[Image:sharpened_bbc.jpg|right]]
<langsyntaxhighlight lang="bbcbasic"> Width% = 200
Height% = 200
Line 262:
REPEAT
WAIT 1
UNTIL FALSE</langsyntaxhighlight>
 
=={{header|C}}==
Line 268:
Interface:
 
<langsyntaxhighlight lang="c">image filter(image img, double *K, int Ks, double, double);</langsyntaxhighlight>
 
The implementation (the <tt>Ks</tt> argument is so that 1 specifies a 3&times;3 matrix, 2 a 5&times;5 matrix ...
N a (2N+1)&times;(2N+1) matrix).
 
<langsyntaxhighlight lang="c">#include "imglib.h"
 
inline static color_component GET_PIXEL_CHECK(image img, int x, int y, int l) {
Line 311:
}
return NULL;
}</langsyntaxhighlight>
 
Usage example:
Line 317:
The <tt>read_image</tt> function is from [[Read image file through a pipe|here]].
 
<langsyntaxhighlight lang="c">#include <stdio.h>
#include "imglib.h"
 
Line 377:
free_img(ii);
} else { fprintf(stderr, "err reading %s\n", input); }
}</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
Uses the RGB pixel buffer package defined here [[Basic bitmap storage#Common Lisp]]. Also the PPM file IO functions defined in
[[Bitmap/Read a PPM file#Common_Lisp]] and [[Bitmap/Write a PPM file#Common_Lisp]] merged into one package.
<langsyntaxhighlight lang="lisp">(load "rgb-pixel-buffer")
(load "ppm-file-io")
 
Line 450:
(loop for pars being the hash-values of convolve::*cnv-lib*
do (princ (convolve::convolve "lena_color.ppm" pars)) (terpri)))
</syntaxhighlight>
</lang>
 
=={{header|D}}==
This requires the module from the Grayscale Image Task.
<langsyntaxhighlight lang="d">import std.string, std.math, std.algorithm, grayscale_image;
 
struct ConvolutionFilter {
Line 569:
img.convolve(filter)
.savePGM(format("lenna_gray_%s.ppm", filter.name));
}</langsyntaxhighlight>
 
=={{header|Go}}==
Using standard image library:
<langsyntaxhighlight lang="go">package main
 
import (
Line 663:
fmt.Println(err)
}
}</langsyntaxhighlight>
Alternative version, building on code from bitmap task.
 
New function for raster package:
<langsyntaxhighlight lang="go">package raster
 
import "math"
Line 738:
}
return r
}</langsyntaxhighlight>
Demonstration program:
<langsyntaxhighlight lang="go">package main
 
// Files required to build supporting package raster are found in:
Line 779:
fmt.Println(err)
}
}</langsyntaxhighlight>
 
=={{header|J}}==
 
<langsyntaxhighlight Jlang="j">NB. pad the edges of an array with border pixels
NB. (increasing the first two dimensions by 1 less than the kernel size)
pad=: adverb define{{
rank=.#$m
'a b'=. (<. ,. >.) 0.5 0.5 p. $m
'first second'=. (<.,:>.)-:$m
a"_`(0 , ] - 1:)`(# 1:)}~&# # b"_`(0 , ] - 1:)`(# 1:)}~&(1 { $) #"1 ]
-@(second+rank{.$) {. (first+rank{.$){.]
)
}}
 
kernel_filter=: adverb define{{
[: (0 >. 255 <. <.@:+&0.5) (1,:$m)+/ .*&(,m)~&(,/)&m;._3 m pad
}}</syntaxhighlight>
)</lang>
 
 
Line 799 ⟶ 800:
Example use:
 
<syntaxhighlight lang J="j"> NB. kernels borrowed from C and TCL implementations
sharpen_kernelid_kernel=: _1+10*4(=&i.-)3 3
sharpen_kernel=: ({ _1,#@,)id_kernel
blur_kernel=: ($ *&%/)3 3$%9
emboss_kernel=: _2 _1 0,_1 1 1,:0 1 2
emboss_kernel=: id_kernel+(+/~ - >./)i.3
sobel_emboss_kernel=: _1 _2 _1,0,(i:-:<:3)*/1 2 1+(<.|.)i.3
 
'blurred.ppm' writeppm~ blur_kernel kernel_filter readppm 'original.ppm'</langsyntaxhighlight>
 
=={{header|Java}}==
 
'''Code:'''
<langsyntaxhighlight Javalang="java">import java.awt.image.*;
import java.io.File;
import java.io.IOException;
Line 950 ⟶ 952:
return;
}
}</langsyntaxhighlight>
 
 
Line 965 ⟶ 967:
 
'''Code:'''
<langsyntaxhighlight lang="javascript">// Image imageIn, Array kernel, function (Error error, Image imageOut)
// precondition: Image is loaded
// returns loaded Image to asynchronous callback function
Line 1,040 ⟶ 1,042:
imageOut.src = can.toDataURL('image/png');
}</langsyntaxhighlight>
 
'''Example Usage:'''
Line 1,068 ⟶ 1,070:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">
using FileIO, Images
 
Line 1,078 ⟶ 1,080:
 
save("imagesharper.png", imfilt)
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">// version 1.2.10
 
import kotlin.math.round
Line 1,197 ⟶ 1,199:
}
writeOutputImage(args[1], dataArrays)
}</langsyntaxhighlight>
 
{{out}}
Line 1,210 ⟶ 1,212:
<br>
NB Things like convolution would be best done by combining LB with ImageMagick, which is easily called from LB.
<syntaxhighlight lang="lb">
<lang lb>
dim result( 300, 300), image( 300, 300), mask( 100, 100)
w =128
Line 1,306 ⟶ 1,308:
CallDLL #user32, "ReleaseDC", hw as ulong, hdc as ulong
end
</syntaxhighlight>
</lang>
Screenview is available at [[http://www.diga.me.uk/convolved.gif]]
 
=={{header|Maple}}==
Builtin command ImageTools:-Convolution()
<langsyntaxhighlight Maplelang="maple">pic:=Import("smiling_dog.jpg"):
mask := Matrix([[1,2,3],[4,5,6],[7,8,9]]);
pic := ImageTools:-Convolution(pic, mask);</langsyntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Most image processing functions introduced in Mathematica 7
<langsyntaxhighlight lang="mathematica">img = Import[NotebookDirectory[] <> "Lenna50.jpg"];
kernel = {{0, -1, 0}, {-1, 4, -1}, {0, -1, 0}};
ImageConvolve[img, kernel]
ImageConvolve[img, GaussianMatrix[35] ]
ImageConvolve[img, BoxMatrix[1] ]</langsyntaxhighlight>
 
=={{header|MATLAB}}==
The built-in function [http://www.mathworks.com/help/matlab/ref/conv2.html conv2] handles the basic convolution. Below is a program that has several more options that may be useful in different image processing applications (see comments under convImage for specifics).
<langsyntaxhighlight MATLABlang="matlab">function testConvImage
Im = [1 2 1 5 5 ; ...
1 2 7 9 9 ; ...
Line 1,492 ⟶ 1,494:
% Convert back to former image data type
ImOut = cast(ImOut, classIm);
end</langsyntaxhighlight>
{{out}}
<pre>Original image:
Line 1,546 ⟶ 1,548:
As in the D version, we use the modules built for the "bitmap" and "grayscale image" tasks. But we have chosen to read and write PNG files rather than PPM files, using for this purpose the "nimPNG" third party module.
 
<langsyntaxhighlight Nimlang="nim">import math, lenientops, strutils
import nimPNG, bitmap, grayscale_image
 
Line 1,663 ⟶ 1,665:
let output = Output2.format(filter.name)
if savePNG24(output, data, result.w, result.h).isOk:
echo "Saved: ", output</langsyntaxhighlight>
 
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let get_rgb img x y =
let _, r_channel,_,_ = img in
let width = Bigarray.Array2.dim1 r_channel
Line 1,721 ⟶ 1,723:
done;
done;
(res)</langsyntaxhighlight>
 
<langsyntaxhighlight lang="ocaml">let emboss img =
let kernel = [|
[| -2.; -1.; 0. |];
Line 1,757 ⟶ 1,759:
|] in
convolve_value ~img ~kernel ~divisor:9.0 ~offset:0.0;
;;</langsyntaxhighlight>
 
=={{header|Octave}}==
Line 1,763 ⟶ 1,765:
'''Use package''' [http://octave.sourceforge.net/image/index.html Image]
 
<langsyntaxhighlight lang="octave">function [r, g, b] = rgbconv2(a, c)
r = im2uint8(mat2gray(conv2(a(:,:,1), c)));
g = im2uint8(mat2gray(conv2(a(:,:,2), c)));
Line 1,785 ⟶ 1,787:
jpgwrite("LennaSobel.jpg", r, g, b, 100);
[r, g, b] = rgbconv2(im, sharpen);
jpgwrite("LennaSharpen.jpg", r, g, b, 100);</langsyntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use strict;
use warnings;
 
Line 1,798 ⟶ 1,800:
my $image = rpic 'pythagoras_tree.png';
my $smoothed = conv2d $image, $kernel, {Boundary => 'Truncate'};
wpic $smoothed, 'pythagoras_convolution.png';</langsyntaxhighlight>
Compare offsite images: [https://github.com/SqrtNegInf/Rosettacode-Perl5-Smoke/blob/master/ref/frog.png frog.png] vs.
[https://github.com/SqrtNegInf/Rosettacode-Perl5-Smoke/blob/master/ref/frog_convolution.png frog_convolution.png]
Line 1,804 ⟶ 1,806:
=={{header|Phix}}==
{{libheader|Phix/pGUI}}
<!--<langsyntaxhighlight Phixlang="phix">(notonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Image_convolution.exw
Line 1,922 ⟶ 1,924:
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</langsyntaxhighlight>-->
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(scl 3)
 
(de ppmConvolution (Ppm Kernel)
Line 1,949 ⟶ 1,951:
(* (get X K L C) (get Kernel K L)) ) ) )
(link (min 255 (max 0 (*/ Val 1.0)))) ) ) ) )
(map pop X) ) ) ) ) ) ) )</langsyntaxhighlight>
Test using 'ppmRead' from [[Bitmap/Read a PPM file#PicoLisp]] and 'ppmWrite'
from [[Bitmap/Write a PPM file#PicoLisp]]:
Line 1,969 ⟶ 1,971:
Image manipulation is normally done using an image processing library. For PIL/Pillow do:
 
<langsyntaxhighlight lang="python">#!/bin/python
from PIL import Image, ImageFilter
 
Line 1,980 ⟶ 1,982:
im2 = im.filter(kernel)
 
im2.show()</langsyntaxhighlight>
 
Alternatively, SciPy can be used but programmers need to be careful about the colors being clipped since they are normally limited to the 0-255 range:
 
<langsyntaxhighlight lang="python">#!/bin/python
import numpy as np
from scipy.ndimage.filters import convolve
Line 2,000 ⟶ 2,002:
im3 = np.array(np.clip(im2, 0, 255), dtype=np.uint8) #Apply color clipping
imshow(im3)</langsyntaxhighlight>
 
=={{header|Racket}}==
Line 2,010 ⟶ 2,012:
 
 
<langsyntaxhighlight lang="racket">#lang typed/racket
(require images/flomap racket/flonum)
 
Line 2,059 ⟶ 2,061:
(save-image
(flomap->bitmap (flomap-convolve flmp (flvector -1. -1. -1. -1. 4. -1. -1. -1. -1.)))
"out/convolve-etch-3x3.png"))</langsyntaxhighlight>
 
=={{header|Raku}}==
Line 2,065 ⟶ 2,067:
===Perl 5 PDL library===
 
<syntaxhighlight lang="raku" perl6line>use PDL:from<Perl5>;
use PDL::Image2D:from<Perl5>;
 
Line 2,072 ⟶ 2,074:
my $image = rpic 'frog.png';
my $smoothed = conv2d $image, $kernel, {Boundary => 'Truncate'};
wpic $smoothed, 'frog_convolution.png';</langsyntaxhighlight>
Compare offsite images: [https://github.com/SqrtNegInf/Rosettacode-Perl6-Smoke/blob/master/ref/frog.png frog.png] vs.
[https://github.com/SqrtNegInf/Rosettacode-Perl6-Smoke/blob/master/ref/frog_convolution.png frog_convolution.png]
 
===Imagemagick library===
<syntaxhighlight lang="raku" line>
<lang perl6>
# Note: must install version from github NOT version from CPAN which needs to be updated.
# Reference:
Line 2,107 ⟶ 2,109:
$original.cleanup if $original.defined;
$o.cleanup if $o.defined;
}</langsyntaxhighlight>
 
=={{header|Ruby}}==
{{trans|Tcl}}
<langsyntaxhighlight lang="ruby">class Pixmap
# Apply a convolution kernel to a whole image
def convolute(kernel)
Line 2,167 ⟶ 2,169:
savefile = 'teapot_' + label.downcase + '.ppm'
teapot.convolute(kernel).save(savefile)
end</langsyntaxhighlight>
 
=={{header|Tcl}}==
{{works with|Tcl|8.6}}
{{libheader|Tk}}
<langsyntaxhighlight lang="tcl">package require Tk
 
# Function for clamping values to those that we can use with colors
Line 2,248 ⟶ 2,250:
pack [labelframe .$name -text $label] -side left
pack [label .$name.l -image [convolve teapot $kernel]]
}</langsyntaxhighlight>
 
=={{header|Wren}}==
{{libheader|DOME}}
Based on the Java/Kotlin solutions, though input details are hard-coded rather than read in as command line arguments and the input and output images are displayed side by side with the latter also being saved to a file.
<langsyntaxhighlight ecmascriptlang="wren">import "graphics" for Canvas, Color, ImageData
import "dome" for Window
 
Line 2,331 ⟶ 2,333:
 
getArrayDatasFromImage(filename) {
var inputImage = ImageData.loadFromFileload(filename)
inputImage.draw(0, 0)
Canvas.print(filename, _width * 1/6, _height * 5/6, Color.white)
Line 2,399 ⟶ 2,401:
for (x in 0...k.count) kernel[x, y] = k[x][y]
}
var Game = ImageConvolution.new(700, 300, image1, image2, kernel, divisor)</langsyntaxhighlight>
 
{{out}}
9,476

edits