Percentage difference between images: Difference between revisions
Percentage difference between images (view source)
Revision as of 00:43, 20 April 2024
, 29 days ago"Ada" section: Correct reference to "Left.G" to "Right.G".
m (→{{header|Phix}}: syntax coloured, marked p2js incompatible) |
Flexibeast (talk | contribs) ("Ada" section: Correct reference to "Left.G" to "Right.G".) |
||
(2 intermediate revisions by 2 users not shown) | |||
Line 20:
=={{header|Ada}}==
<
[[wp:Distance|1-norm distance]] in the luminance space:
<
begin
if Left > Right then
Line 29:
return Count (Right) - Count (Left);
end if;
end "-";</
1-norm distance in the color space multiplied to 3:
<
begin
return (Left.R - Right.R) + (Left.G -
end "-";</
Mean of 1-norm distances. Constraint_Error is propagated when images have different size.
<
Offs_I : constant Integer := Right'First (1) - Left'First (1);
Offs_J : constant Integer := Right'First (2) - Left'First (2);
Line 50:
end loop;
return Float (Sum) / (3.0 * Float (Left'Length (1) * Left'Length (2)));
end Diff;</
Example of use:
<
begin
Open (F1, In_File, "city.ppm");
Line 58:
Ada.Text_IO.Put_Line ("Diff" & Float'Image (Diff (Get_PPM (F1), Get_PPM (F2))));
Close (F1);
Close (F2);</
=={{header|AutoHotkey}}==
{{works with | AutoHotkey_L}}
uses [http://www.autohotkey.com/forum/topic32238.html gdip.ahk]
<
dibSection := getPixels("lenna100.jpg")
dibSection2 := getPixels("lenna50.jpg") ; ("File-Lenna100.jpg")
Line 148:
}
#Include Gdip.ahk ; Thanks to tic (Tariq Porter) for his GDI+ Library
</syntaxhighlight>
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
I would have preferred to calculate the RMS difference but it would be inconsistent with other results.
<
hbm2% = FNloadimage("C:lenna100.jpg")
Line 200:
SYS !(!pic%+12), pic%, ^hbm% : REM. IPicture::get_Handle
SYS "FreeLibrary", ole%
= hbm%</
'''Output:'''
<pre>
Line 210:
The <tt>read_image</tt> function is from [[Read image file through a pipe|here]].
<
#include <stdlib.h>
#include <math.h>
Line 254:
free_img(im1);
free_img(im2);
}</
The output on Lenna is:
Line 264:
=={{header|C sharp|C#}}==
<
using System.Drawing;
Line 297:
Console.WriteLine("diff: {0} %", 100 * (diff / 255) / (img1.Width * img1.Height * 3));
}
}</
=={{header|C++}}==
based upon C version, using Qt 4.4
<
#include <cstdlib>
#include <QColor>
Line 344:
(totaldiff * 100) / (w * h * 3) << " % !\n" ;
return 0 ;
}</
output on pictures given;
Line 355:
This is based upon the C version. Strangely enough, the percentage is 1.77% which is off by about a tenth of a percent.
<
;;; the JPEG library uses simple-vectors to store data. this is insane!
(defun compare-images (file1 file2)
Line 368:
CL-USER> (* 100 (compare-images "Lenna50.jpg" "Lenna100.jpg"))
1.774856467652165d0</
=={{header|D}}==
{{trans|Python}}
<
void main() {
Line 388:
writeln("Difference (percentage): ",
(dif / 255.0 * 100) / nData);
}</
{{out}}
<pre>Difference (percentage): 1.62559</pre>
Line 396:
By dividing only at the end, we work with integers only as the sum and avoid floating-point error from adding small numbers (per-pixel difference) to large ones (sum of differences).
<
require(a.width() == b.width())
require(a.height() == b.height())
Line 424:
def d := imageDifference(a, b)
println(`${d * 100}% different.`)
}</
The result on the provided images is 1.6255930981604882%.
=={{header|F_Sharp|F#}}==
<
//Percentage difference between 2 images. Nigel Galloway April 18th., 2018
let img50 = new System.Drawing.Bitmap("Lenna50.jpg")
let img100 = new System.Drawing.Bitmap("Lenna100.jpg")
let diff=Seq.cast<System.Drawing.Color*System.Drawing.Color>(Array2D.init img50.Width img50.Height (fun n g->(img50.GetPixel(n,g),img100.GetPixel(n,g))))|>Seq.fold(fun i (e,l)->i+abs(int(e.R)-int(l.R))+abs(int(e.B)-int(l.B))+abs(int(e.G)-int(l.G))) 0
printfn "%f" ((float diff)*100.00/(float(img50.Height*img50.Width)*255.0*3.0))</
{{out}}
<pre>
Line 441:
=={{header|Forth}}==
<
over 255 and over 255 and - abs >r 8 rshift swap 8 rshift
over 255 and over 255 and - abs >r 8 rshift swap 8 rshift
Line 457:
: .bdiff ( bmp1 bmp2 -- )
cr bdiff 100e f* f. ." percent different" ;</
=={{header|Fortran}}==
<
use RCImageBasic
Line 492:
call free_img(lenna2)
end program ImageDifference</
This gives 1.6555154.
Line 498:
=={{header|Frink}}==
<
img1 = new image["file:Lenna50.jpg"]
img2 = new image["file:Lenna100.jpg"]
Line 516:
errors = sum / (w1 * h1 * 3)
println["Error is " + (errors->"percent")]
</syntaxhighlight>
This gives an error of approximately 1.625593 percent.
Line 522:
=={{header|Go}}==
Using standard image library:
<
import (
Line 588:
fmt.Printf("Image difference: %f%%\n",
float64(sum*100)/(float64(nPixels)*0xffff*3))
}</
Output:
<pre>
Line 594:
</pre>
Using code from bitmap task:
<
// Files required to build supporting package raster are found in:
Line 665:
fmt.Printf("Image difference: %f%%\n",
float64(sum)*100/(float64(b1c*b1r)*255*3))
}</
Output:
<pre>
Line 675:
This implementation takes PPMs as input. It uses modules defined in [[Basic bitmap storage]] and [[Write ppm file]].
<
import Bitmap.Netpbm
import Bitmap.RGB
Line 700:
toEnum (3 * 255 * length i1)
where (RGB (r1, g1, b1)) `minus` (RGB (r2, g2, b2)) =
abs (r1 - r2) + abs (g1 - g2) + abs (b1 - b2)</
=={{header|Icon}} and {{header|Unicon}}==
Line 706:
The Icon and Unicon graphics facilities are under documented with respect to some features. Unicon can support reading and writing to a number of additional image formats. I'm not sure if this will run under Icon or not. Some minor reworking of the open would be the minimum requirement; however, Icon may not have read support for jpg files.
<
procedure main() # % difference between images
Line 739:
}
return L
end</
Output:<pre>%difference of files "Lenna100.jpg" & "Lenna50.jpg" = 1.625587</pre>
=={{header|J}}==
<
'Lenna50.jpg' (+/@,@:|@:- % 2.55 * */@$@])&read_image 'Lenna100.jpg'
1.62559</
=={{header|Java}}==
<
import java.io.File;
import java.io.IOException;
Line 797:
return Math.abs(r1 - r2) + Math.abs(g1 - g2) + Math.abs(b1 - b2);
}
}</
=={{header|JavaScript}}==
<
var img = document.createElement('img');
var canvas = document.createElement('canvas');
Line 839:
compare('Lenna50.jpg', 'Lenna100.jpg', function (result) {
console.log(result);
});</
=={{header|Julia}}==
<
absdiff(a::RGB{T}, b::RGB{T}) where T = sum(abs(col(a) - col(b)) for col in (red, green, blue))
Line 858:
d = pctdiff(img50, img100)
@printf("Percentage difference: %.4f%%\n", d)</
{{out}}
Line 865:
=={{header|Kotlin}}==
{{trans|Java}}
<
import java.awt.image.BufferedImage
Line 907:
val p = getDifferencePercent(img1, img2)
println("The percentage difference is ${"%.6f".format(p)}%")
}</
{{out}}
Line 916:
=={{header|Lua}}==
Using the Bitmap class from [[Bitmap/Bresenham%27s_line_algorithm#Lua|here]] and ImageMagick to preprocess jpg->ppm to simplify loading:
<
local fp = io.open( filename, "rb" )
if fp == nil then return false end
Line 950:
bm100:loadPPM("Lenna100.ppm")
print("%diff:", bm100:percentageDifference(bm50))</
{{out}}
<pre>%diff: 1.6255930981605</pre>
Line 957:
LB uses here a DLL to allow loading the jpgs. I get the 'other' result if I use LB's native bmp load and convert the jpgs to bmp with the Gimp!
The GUI shows the 'difference image'. [http://www.diga.me.uk/right.gif SceenDisplay]
<syntaxhighlight lang="lb">
now =time$( "seconds")
nomainwin
Line 1,039:
close #j
end
</syntaxhighlight>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
img100 = ImageData@Import[NotebookDirectory[] <> "Lenna100.jpg"];
diff = img50 - img100;
Print["Total Difference between both Lenas = ",
Total@Abs@Flatten@diff/Times @@ Dimensions@img50*100, "%"]</
'''Output'''
Line 1,052:
=={{header|MATLAB}}==
<syntaxhighlight lang="matlab">
% Percentage difference between images
function p = PercentageDifferenceBetweenImages(im1,im2)
Line 1,063:
p = sum(d(:))./numel(im1)*100;
disp(['Percentage difference between images is: ', num2str(p), '%'])</
'''Output'''
Line 1,069:
=={{header|MAXScript}}==
<
(
local img1 = selectBitmap caption:"Select Image 1"
Line 1,087:
)
format "Diff: %\%\n" (totalDiff / ((img1.width * img1.height * 3) as float) * 100)
)</
=={{header|Nim}}==
{{libheader|imageman}}
We use the procedure <code>loadImage</code> which sets default values for JPEG decoding parameters. With these parameters, the difference between the images is about 1.7747 %. Using the less convenient procedure <code>readImage</code> which works on an open file, it is possible to change the parameters in order to get the smaller difference of 1.6256 %.
<
import imageman
Line 1,116:
sum += abs(color1[i].int - color2[i].int)
echo &"Image difference: {sum * 100 / (width * height * 3 * 255):.4f} %"</
{{out}}
Line 1,124:
{{libheader|glMLite}}
<
#directory "+glMLite/"
#load "jpeg_loader.cma"
Line 1,159:
let diff_percent = !sum /. float !num in
Printf.printf " diff: %f percent\n" diff_percent;
;;</
=={{header|Perl}}==
<
my $img1 = Image::Imlib2->load('Lenna50.jpg') || die;
Line 1,180:
}
printf "%% difference = %.4f\n", 100 * $sum / ($w * $h * 3 * 255);</
{{out}}
<pre>% difference = 1.7747</pre>
Alternative solution:
<
use List::AllUtils qw(sum pairwise);
Line 1,213:
}
printf "difference = %f%%\n", 100 * img_diff('Lenna50.jpg', 'Lenna100.jpg');</
{{out}}
<pre>
Line 1,220:
=={{header|Phix}}==
<!--<
<span style="color: #000080;font-style:italic;">-- demo\rosetta\Percentage_difference_between_images.exw</span>
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (file i/o)</span>
Line 1,251:
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">wait_key</span><span style="color: #0000FF;">()</span>
<!--</
{{out}}
<pre>
Line 1,258:
=={{header|PicoLisp}}==
<
(call "convert" "Lenna100.jpg" (tmp "Lenna100.ppm"))
Line 1,271:
255 ) )
(inc 'Total) ) ) )
(prinl "Difference is " (format (*/ Diff Total) 4) " percent") )</
Output:
<pre>Difference is 1.6256 percent</pre>
Line 1,277:
=={{header|PureBasic}}==
This program downloads both jpg files, decodes them & saves them in 2D-arrays for simple comparison which part is comparable with the other languages.
<
#URL2="http://rosettacode.org/mw/images/b/b6/Lenna100.jpg"
Line 1,328:
Next x
MessageRequester("Result","Diff= "+StrD(100*totalDiff/(255*w*h*3),3)+" %")</
=={{header|Python}}==
Line 1,334:
{{works with|python version 3.x}}
<
i1 = Image.open("image1.jpg")
Line 1,349:
ncomponents = i1.size[0] * i1.size[1] * 3
print ("Difference (percentage):", (dif / 255.0 * 100) / ncomponents)</
{{works with|python version 2.x}}
<
import Image
Line 1,368:
ncomponents = i1.size[0] * i1.size[1] * 3
print "Difference (percentage):", (dif / 255.0 * 100) / ncomponents</
=={{header|Racket}}==
Line 1,374:
Note: On OS X I get 1.6192% as the result. (soegaard)
<
(require racket/draw)
Line 1,395:
(define lenna100 (read-bitmap "lenna100.jpg"))
(percentage-difference lenna50 lenna100) ;-> 1.7749329408009846</
=={{header|Raku}}==
Line 1,401:
Using [https://modules.raku.org/search/?q=GD%3A%3ARaw GD::Raw from the Raku ecosystem].
<syntaxhighlight lang="raku"
my $fh1 = fopen('./Lenna50.jpg', "rb") or die;
Line 1,433:
gdImageDestroy($img1);
gdImageDestroy($img2);
</syntaxhighlight>
{{out}}
<pre>
Line 1,440:
=={{header|REBOL}}==
<
Title: "Percent Image Difference"
URL: http://rosettacode.org/wiki/Percentage_of_difference_between_2_images
Line 1,489:
button "b" #"b" [flip 'b]
button "difference" #"d" [flip 'diff]
]</
Output:
Line 1,501:
=={{header|Ruby}}==
uses the <code>[[Raster graphics operations/Ruby|raster_graphics]]</code> library
<
class RGBColour
Line 1,527:
lenna100 = Pixmap.open_from_jpeg('Lenna100.jpg')
puts "difference: %.5f%%" % (100.0 * (lenna50 - lenna100))</
produces:
Line 1,533:
=={{header|Rust}}==
<
use image::{GenericImageView, Rgba};
Line 1,552:
}
println!("Percent difference {}", accum as f64 * 100.0/ (255.0 * 3.0 * (img1.width() * img1.height()) as f64));
}</
produces:
Line 1,558:
=={{header|Sidef}}==
<
func img_diff(a, b) {
Line 1,595:
}
say 100*img_diff('Lenna50.jpg', 'Lenna100.jpg')</
{{out}}
<pre>
Line 1,602:
=={{header|Swift}}==
<
{
var width = 0
Line 1,657:
compareImages(image1: image1, image2: image2)
</syntaxhighlight>
=={{header|Tcl}}==
{{libheader|Tk}}
This version uses the '''Img''' package, but only to provide a convenient JPEG loader; it's utterly unnecessary for the process of actually computing the difference.
<
proc imageDifference {img1 img2} {
Line 1,687:
image create photo lenna100 -file lenna100.jpg
puts "difference is [expr {[imageDifference lenna50 lenna100]*100.}]%"
exit ;# Need explicit exit here; don't want a GUI</
It produces this output:
difference is 1.6255930981604882%
Line 1,694:
This implementation compares two BMP images.
<
File_Open("Lenna50.bmp", BROWSE)
#10 = Buf_Num // #10 = buffer for 1st image
Line 1,723:
Buf_Switch(#10) Buf_Quit(OK)
Buf_Switch(#20) Buf_Quit(OK)</
Output, when comparing the Lenna images that were converted to BMP:
Line 1,735:
{{trans|Kotlin}}
{{libheader|DOME}}
<
import "dome" for Window
Line 1,783:
}
var Game = PercentageDifference.new(1100, 550, "Lenna50.jpg", "Lenna100.jpg")</
{{out}}
Line 1,792:
=={{header|zkl}}==
Uses the PPM class from http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm#zkl
<
if(img1.w!=img2.w or img1.h!=img2.h)
throw(Exception.ValueError("width/height of the images must match!"));
Line 1,798:
.reduce(fcn(totalDiff,[(a,b)]){ totalDiff + (a - b).abs() },0)
.toFloat()/img1.w/img1.h/3/255; // or: .toFloat()/img1.data.len()/255
}</
Take the bytes in each image, zip them together [lazily], sum the differences between each byte and normalize.
<
p:=System.popen("convert \"%s\" ppm:-".fmt(fileName),"r");
img:=PPM.readPPM(p);
p.close();
img
}</
Use the convert utility from ImageMagick to convert a JPEG image to PPM.
<
"Image difference = %f%%".fmt(_*100).println();</
Compute the diff between the two Lennas, format and print it. More conventionally, this would be written as
<
imageDiff(readJPG2PPM("lenna50.jpg"),readJPG2PPM("lenna100.jpg")) * 100)
);</
{{out}}
<pre>
|