Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Port the provided Ada code into C while preserving the original functionality. | type Count is mod 2**64;
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define RED_C 0
#define GREEN_C 1
#define BLUE_C 2
#define GET_PIXEL(IMG, X, Y) ((IMG)->buf[ (Y) * (IMG)->width + (X) ])
int main(int argc, char **argv)
{
image im1, im2;
double totalDiff = 0.0;
unsigned int x, y;
if ( argc < 3 )
{
fprintf(stderr, "usage:\n%s FILE1 FILE2\n", argv[0]);
exit(1);
}
im1 = read_image(argv[1]);
if ( im1 == NULL ) exit(1);
im2 = read_image(argv[2]);
if ( im2 == NULL ) { free_img(im1); exit(1); }
if ( (im1->width != im2->width) || (im1->height != im2->height) )
{
fprintf(stderr, "width/height of the images must match!\n");
} else {
for(x=0; x < im1->width; x++)
{
for(y=0; y < im1->width; y++)
{
totalDiff += fabs( GET_PIXEL(im1, x, y)[RED_C] - GET_PIXEL(im2, x, y)[RED_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[GREEN_C] - GET_PIXEL(im2, x, y)[GREEN_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[BLUE_C] - GET_PIXEL(im2, x, y)[BLUE_C] ) / 255.0;
}
}
printf("%lf\n", 100.0 * totalDiff / (double)(im1->width * im1->height * 3) );
}
free_img(im1);
free_img(im2);
}
|
Translate this program into C++ but keep the logic exactly as in Ada. | type Count is mod 2**64;
| #include <QImage>
#include <cstdlib>
#include <QColor>
#include <iostream>
int main( int argc , char *argv[ ] ) {
if ( argc != 3 ) {
std::cout << "Call this with imagecompare <file of image 1>"
<< " <file of image 2>\n" ;
return 1 ;
}
QImage firstImage ( argv[ 1 ] ) ;
QImage secondImage ( argv[ 2 ] ) ;
double totaldiff = 0.0 ;
int h = firstImage.height( ) ;
int w = firstImage.width( ) ;
int hsecond = secondImage.height( ) ;
int wsecond = secondImage.width( ) ;
if ( w != wsecond || h != hsecond ) {
std::cerr << "Error, pictures must have identical dimensions!\n" ;
return 2 ;
}
for ( int y = 0 ; y < h ; y++ ) {
uint *firstLine = ( uint* )firstImage.scanLine( y ) ;
uint *secondLine = ( uint* )secondImage.scanLine( y ) ;
for ( int x = 0 ; x < w ; x++ ) {
uint pixelFirst = firstLine[ x ] ;
int rFirst = qRed( pixelFirst ) ;
int gFirst = qGreen( pixelFirst ) ;
int bFirst = qBlue( pixelFirst ) ;
uint pixelSecond = secondLine[ x ] ;
int rSecond = qRed( pixelSecond ) ;
int gSecond = qGreen( pixelSecond ) ;
int bSecond = qBlue( pixelSecond ) ;
totaldiff += std::abs( rFirst - rSecond ) / 255.0 ;
totaldiff += std::abs( gFirst - gSecond ) / 255.0 ;
totaldiff += std::abs( bFirst -bSecond ) / 255.0 ;
}
}
std::cout << "The difference of the two pictures is " <<
(totaldiff * 100) / (w * h * 3) << " % !\n" ;
return 0 ;
}
|
Translate the given Ada code snippet into Go without altering its behavior. | type Count is mod 2**64;
| package main
import (
"fmt"
"image/jpeg"
"os"
"log"
"image"
)
func loadJpeg(filename string) (image.Image, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
img, err := jpeg.Decode(f)
if err != nil {
return nil, err
}
return img, nil
}
func diff(a, b uint32) int64 {
if a > b {
return int64(a - b)
}
return int64(b - a)
}
func main() {
i50, err := loadJpeg("Lenna50.jpg")
if err != nil {
log.Fatal(err)
}
i100, err := loadJpeg("Lenna100.jpg")
if err != nil {
log.Fatal(err)
}
if i50.ColorModel() != i100.ColorModel() {
log.Fatal("different color models")
}
b := i50.Bounds()
if !b.Eq(i100.Bounds()) {
log.Fatal("different image sizes")
}
var sum int64
for y := b.Min.Y; y < b.Max.Y; y++ {
for x := b.Min.X; x < b.Max.X; x++ {
r1, g1, b1, _ := i50.At(x, y).RGBA()
r2, g2, b2, _ := i100.At(x, y).RGBA()
sum += diff(r1, r2)
sum += diff(g1, g2)
sum += diff(b1, b2)
}
}
nPixels := (b.Max.X - b.Min.X) * (b.Max.Y - b.Min.Y)
fmt.Printf("Image difference: %f%%\n",
float64(sum*100)/(float64(nPixels)*0xffff*3))
}
|
Change the programming language of this snippet from Ada to Java without modifying what it does. | type Count is mod 2**64;
| import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public enum ImgDiffPercent {
;
public static void main(String[] args) throws IOException {
BufferedImage img1 = ImageIO.read(new File("Lenna50.jpg"));
BufferedImage img2 = ImageIO.read(new File("Lenna100.jpg"));
double p = getDifferencePercent(img1, img2);
System.out.println("diff percent: " + p);
}
private static double getDifferencePercent(BufferedImage img1, BufferedImage img2) {
int width = img1.getWidth();
int height = img1.getHeight();
int width2 = img2.getWidth();
int height2 = img2.getHeight();
if (width != width2 || height != height2) {
throw new IllegalArgumentException(String.format("Images must have the same dimensions: (%d,%d) vs. (%d,%d)", width, height, width2, height2));
}
long diff = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
diff += pixelDiff(img1.getRGB(x, y), img2.getRGB(x, y));
}
}
long maxDiff = 3L * 255 * width * height;
return 100.0 * diff / maxDiff;
}
private static int pixelDiff(int rgb1, int rgb2) {
int r1 = (rgb1 >> 16) & 0xff;
int g1 = (rgb1 >> 8) & 0xff;
int b1 = rgb1 & 0xff;
int r2 = (rgb2 >> 16) & 0xff;
int g2 = (rgb2 >> 8) & 0xff;
int b2 = rgb2 & 0xff;
return Math.abs(r1 - r2) + Math.abs(g1 - g2) + Math.abs(b1 - b2);
}
}
|
Produce a language-to-language conversion: from Ada to Python, same semantics. | type Count is mod 2**64;
| from PIL import Image
i1 = Image.open("image1.jpg")
i2 = Image.open("image2.jpg")
assert i1.mode == i2.mode, "Different kinds of images."
assert i1.size == i2.size, "Different sizes."
pairs = zip(i1.getdata(), i2.getdata())
if len(i1.getbands()) == 1:
dif = sum(abs(p1-p2) for p1,p2 in pairs)
else:
dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2))
ncomponents = i1.size[0] * i1.size[1] * 3
print ("Difference (percentage):", (dif / 255.0 * 100) / ncomponents)
|
Produce a functionally identical C code for the snippet given in Arturo. | REBOL [
Title: "Percent Image Difference"
URL: http://rosettacode.org/wiki/Percentage_of_difference_between_2_images
]
a: load-image http://rosettacode.org/mw/images/3/3c/Lenna50.jpg
b: load-image http://rosettacode.org/mw/images/b/b6/Lenna100.jpg
if a/size <> b/size [print "Image dimensions must match." halt]
diff: to-image layout/tight [image a effect [difference b]]
t: 0
repeat p diff [t: t + p/1 + p/2 + p/3]
print rejoin ["Difference: " 100 * t / (255 * 3 * length? diff) "%"]
flip: func [
"Change to new image and label."
name [word!] "Image to switch to."
][x/text: rejoin ["Image " name] x/image: get name show x]
diff: to-image layout/tight [image diff effect [contrast 100]]
view l: layout [
x: image diff
across
button "a" #"a" [flip 'a]
button "b" #"b" [flip 'b]
button "difference" #"d" [flip 'diff]
]
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define RED_C 0
#define GREEN_C 1
#define BLUE_C 2
#define GET_PIXEL(IMG, X, Y) ((IMG)->buf[ (Y) * (IMG)->width + (X) ])
int main(int argc, char **argv)
{
image im1, im2;
double totalDiff = 0.0;
unsigned int x, y;
if ( argc < 3 )
{
fprintf(stderr, "usage:\n%s FILE1 FILE2\n", argv[0]);
exit(1);
}
im1 = read_image(argv[1]);
if ( im1 == NULL ) exit(1);
im2 = read_image(argv[2]);
if ( im2 == NULL ) { free_img(im1); exit(1); }
if ( (im1->width != im2->width) || (im1->height != im2->height) )
{
fprintf(stderr, "width/height of the images must match!\n");
} else {
for(x=0; x < im1->width; x++)
{
for(y=0; y < im1->width; y++)
{
totalDiff += fabs( GET_PIXEL(im1, x, y)[RED_C] - GET_PIXEL(im2, x, y)[RED_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[GREEN_C] - GET_PIXEL(im2, x, y)[GREEN_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[BLUE_C] - GET_PIXEL(im2, x, y)[BLUE_C] ) / 255.0;
}
}
printf("%lf\n", 100.0 * totalDiff / (double)(im1->width * im1->height * 3) );
}
free_img(im1);
free_img(im2);
}
|
Ensure the translated C# code behaves exactly like the original Arturo snippet. | REBOL [
Title: "Percent Image Difference"
URL: http://rosettacode.org/wiki/Percentage_of_difference_between_2_images
]
a: load-image http://rosettacode.org/mw/images/3/3c/Lenna50.jpg
b: load-image http://rosettacode.org/mw/images/b/b6/Lenna100.jpg
if a/size <> b/size [print "Image dimensions must match." halt]
diff: to-image layout/tight [image a effect [difference b]]
t: 0
repeat p diff [t: t + p/1 + p/2 + p/3]
print rejoin ["Difference: " 100 * t / (255 * 3 * length? diff) "%"]
flip: func [
"Change to new image and label."
name [word!] "Image to switch to."
][x/text: rejoin ["Image " name] x/image: get name show x]
diff: to-image layout/tight [image diff effect [contrast 100]]
view l: layout [
x: image diff
across
button "a" #"a" [flip 'a]
button "b" #"b" [flip 'b]
button "difference" #"d" [flip 'diff]
]
| using System;
using System.Drawing;
class Program
{
static void Main()
{
Bitmap img1 = new Bitmap("Lenna50.jpg");
Bitmap img2 = new Bitmap("Lenna100.jpg");
if (img1.Size != img2.Size)
{
Console.Error.WriteLine("Images are of different sizes");
return;
}
float diff = 0;
for (int y = 0; y < img1.Height; y++)
{
for (int x = 0; x < img1.Width; x++)
{
Color pixel1 = img1.GetPixel(x, y);
Color pixel2 = img2.GetPixel(x, y);
diff += Math.Abs(pixel1.R - pixel2.R);
diff += Math.Abs(pixel1.G - pixel2.G);
diff += Math.Abs(pixel1.B - pixel2.B);
}
}
Console.WriteLine("diff: {0} %", 100 * (diff / 255) / (img1.Width * img1.Height * 3));
}
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the Arturo version. | REBOL [
Title: "Percent Image Difference"
URL: http://rosettacode.org/wiki/Percentage_of_difference_between_2_images
]
a: load-image http://rosettacode.org/mw/images/3/3c/Lenna50.jpg
b: load-image http://rosettacode.org/mw/images/b/b6/Lenna100.jpg
if a/size <> b/size [print "Image dimensions must match." halt]
diff: to-image layout/tight [image a effect [difference b]]
t: 0
repeat p diff [t: t + p/1 + p/2 + p/3]
print rejoin ["Difference: " 100 * t / (255 * 3 * length? diff) "%"]
flip: func [
"Change to new image and label."
name [word!] "Image to switch to."
][x/text: rejoin ["Image " name] x/image: get name show x]
diff: to-image layout/tight [image diff effect [contrast 100]]
view l: layout [
x: image diff
across
button "a" #"a" [flip 'a]
button "b" #"b" [flip 'b]
button "difference" #"d" [flip 'diff]
]
| #include <QImage>
#include <cstdlib>
#include <QColor>
#include <iostream>
int main( int argc , char *argv[ ] ) {
if ( argc != 3 ) {
std::cout << "Call this with imagecompare <file of image 1>"
<< " <file of image 2>\n" ;
return 1 ;
}
QImage firstImage ( argv[ 1 ] ) ;
QImage secondImage ( argv[ 2 ] ) ;
double totaldiff = 0.0 ;
int h = firstImage.height( ) ;
int w = firstImage.width( ) ;
int hsecond = secondImage.height( ) ;
int wsecond = secondImage.width( ) ;
if ( w != wsecond || h != hsecond ) {
std::cerr << "Error, pictures must have identical dimensions!\n" ;
return 2 ;
}
for ( int y = 0 ; y < h ; y++ ) {
uint *firstLine = ( uint* )firstImage.scanLine( y ) ;
uint *secondLine = ( uint* )secondImage.scanLine( y ) ;
for ( int x = 0 ; x < w ; x++ ) {
uint pixelFirst = firstLine[ x ] ;
int rFirst = qRed( pixelFirst ) ;
int gFirst = qGreen( pixelFirst ) ;
int bFirst = qBlue( pixelFirst ) ;
uint pixelSecond = secondLine[ x ] ;
int rSecond = qRed( pixelSecond ) ;
int gSecond = qGreen( pixelSecond ) ;
int bSecond = qBlue( pixelSecond ) ;
totaldiff += std::abs( rFirst - rSecond ) / 255.0 ;
totaldiff += std::abs( gFirst - gSecond ) / 255.0 ;
totaldiff += std::abs( bFirst -bSecond ) / 255.0 ;
}
}
std::cout << "The difference of the two pictures is " <<
(totaldiff * 100) / (w * h * 3) << " % !\n" ;
return 0 ;
}
|
Change the following Arturo code into Java without altering its purpose. | REBOL [
Title: "Percent Image Difference"
URL: http://rosettacode.org/wiki/Percentage_of_difference_between_2_images
]
a: load-image http://rosettacode.org/mw/images/3/3c/Lenna50.jpg
b: load-image http://rosettacode.org/mw/images/b/b6/Lenna100.jpg
if a/size <> b/size [print "Image dimensions must match." halt]
diff: to-image layout/tight [image a effect [difference b]]
t: 0
repeat p diff [t: t + p/1 + p/2 + p/3]
print rejoin ["Difference: " 100 * t / (255 * 3 * length? diff) "%"]
flip: func [
"Change to new image and label."
name [word!] "Image to switch to."
][x/text: rejoin ["Image " name] x/image: get name show x]
diff: to-image layout/tight [image diff effect [contrast 100]]
view l: layout [
x: image diff
across
button "a" #"a" [flip 'a]
button "b" #"b" [flip 'b]
button "difference" #"d" [flip 'diff]
]
| import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public enum ImgDiffPercent {
;
public static void main(String[] args) throws IOException {
BufferedImage img1 = ImageIO.read(new File("Lenna50.jpg"));
BufferedImage img2 = ImageIO.read(new File("Lenna100.jpg"));
double p = getDifferencePercent(img1, img2);
System.out.println("diff percent: " + p);
}
private static double getDifferencePercent(BufferedImage img1, BufferedImage img2) {
int width = img1.getWidth();
int height = img1.getHeight();
int width2 = img2.getWidth();
int height2 = img2.getHeight();
if (width != width2 || height != height2) {
throw new IllegalArgumentException(String.format("Images must have the same dimensions: (%d,%d) vs. (%d,%d)", width, height, width2, height2));
}
long diff = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
diff += pixelDiff(img1.getRGB(x, y), img2.getRGB(x, y));
}
}
long maxDiff = 3L * 255 * width * height;
return 100.0 * diff / maxDiff;
}
private static int pixelDiff(int rgb1, int rgb2) {
int r1 = (rgb1 >> 16) & 0xff;
int g1 = (rgb1 >> 8) & 0xff;
int b1 = rgb1 & 0xff;
int r2 = (rgb2 >> 16) & 0xff;
int g2 = (rgb2 >> 8) & 0xff;
int b2 = rgb2 & 0xff;
return Math.abs(r1 - r2) + Math.abs(g1 - g2) + Math.abs(b1 - b2);
}
}
|
Write a version of this Arturo function in Python with identical behavior. | REBOL [
Title: "Percent Image Difference"
URL: http://rosettacode.org/wiki/Percentage_of_difference_between_2_images
]
a: load-image http://rosettacode.org/mw/images/3/3c/Lenna50.jpg
b: load-image http://rosettacode.org/mw/images/b/b6/Lenna100.jpg
if a/size <> b/size [print "Image dimensions must match." halt]
diff: to-image layout/tight [image a effect [difference b]]
t: 0
repeat p diff [t: t + p/1 + p/2 + p/3]
print rejoin ["Difference: " 100 * t / (255 * 3 * length? diff) "%"]
flip: func [
"Change to new image and label."
name [word!] "Image to switch to."
][x/text: rejoin ["Image " name] x/image: get name show x]
diff: to-image layout/tight [image diff effect [contrast 100]]
view l: layout [
x: image diff
across
button "a" #"a" [flip 'a]
button "b" #"b" [flip 'b]
button "difference" #"d" [flip 'diff]
]
| from PIL import Image
i1 = Image.open("image1.jpg")
i2 = Image.open("image2.jpg")
assert i1.mode == i2.mode, "Different kinds of images."
assert i1.size == i2.size, "Different sizes."
pairs = zip(i1.getdata(), i2.getdata())
if len(i1.getbands()) == 1:
dif = sum(abs(p1-p2) for p1,p2 in pairs)
else:
dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2))
ncomponents = i1.size[0] * i1.size[1] * 3
print ("Difference (percentage):", (dif / 255.0 * 100) / ncomponents)
|
Convert the following code from Arturo to Go, ensuring the logic remains intact. | REBOL [
Title: "Percent Image Difference"
URL: http://rosettacode.org/wiki/Percentage_of_difference_between_2_images
]
a: load-image http://rosettacode.org/mw/images/3/3c/Lenna50.jpg
b: load-image http://rosettacode.org/mw/images/b/b6/Lenna100.jpg
if a/size <> b/size [print "Image dimensions must match." halt]
diff: to-image layout/tight [image a effect [difference b]]
t: 0
repeat p diff [t: t + p/1 + p/2 + p/3]
print rejoin ["Difference: " 100 * t / (255 * 3 * length? diff) "%"]
flip: func [
"Change to new image and label."
name [word!] "Image to switch to."
][x/text: rejoin ["Image " name] x/image: get name show x]
diff: to-image layout/tight [image diff effect [contrast 100]]
view l: layout [
x: image diff
across
button "a" #"a" [flip 'a]
button "b" #"b" [flip 'b]
button "difference" #"d" [flip 'diff]
]
| package main
import (
"fmt"
"image/jpeg"
"os"
"log"
"image"
)
func loadJpeg(filename string) (image.Image, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
img, err := jpeg.Decode(f)
if err != nil {
return nil, err
}
return img, nil
}
func diff(a, b uint32) int64 {
if a > b {
return int64(a - b)
}
return int64(b - a)
}
func main() {
i50, err := loadJpeg("Lenna50.jpg")
if err != nil {
log.Fatal(err)
}
i100, err := loadJpeg("Lenna100.jpg")
if err != nil {
log.Fatal(err)
}
if i50.ColorModel() != i100.ColorModel() {
log.Fatal("different color models")
}
b := i50.Bounds()
if !b.Eq(i100.Bounds()) {
log.Fatal("different image sizes")
}
var sum int64
for y := b.Min.Y; y < b.Max.Y; y++ {
for x := b.Min.X; x < b.Max.X; x++ {
r1, g1, b1, _ := i50.At(x, y).RGBA()
r2, g2, b2, _ := i100.At(x, y).RGBA()
sum += diff(r1, r2)
sum += diff(g1, g2)
sum += diff(b1, b2)
}
}
nPixels := (b.Max.X - b.Min.X) * (b.Max.Y - b.Min.Y)
fmt.Printf("Image difference: %f%%\n",
float64(sum*100)/(float64(nPixels)*0xffff*3))
}
|
Translate this program into C but keep the logic exactly as in AutoHotKey. | startup()
dibSection := getPixels("lenna100.jpg")
dibSection2 := getPixels("lenna50.jpg")
pixels := dibSection.pBits
pixels2 := dibSection2.pBits
z := 0
loop % dibSection.width * dibSection.height * 4
{
x := numget(pixels - 1, A_Index, "uchar")
y := numget(pixels2 - 1, A_Index, "uchar")
z += abs(y - x)
}
msgbox % z / (dibSection.width * dibSection.height * 3 * 255 / 100 )
return
CreateDIBSection2(hDC, nW, nH, bpp = 32, ByRef pBits = "")
{
dib := object()
NumPut(VarSetCapacity(bi, 40, 0), bi)
NumPut(nW, bi, 4)
NumPut(nH, bi, 8)
NumPut(bpp, NumPut(1, bi, 12, "UShort"), 0, "Ushort")
NumPut(0, bi,16)
hbm := DllCall("gdi32\CreateDIBSection", "Uint", hDC, "Uint", &bi, "Uint", 0, "UintP", pBits, "Uint", 0, "Uint", 0)
dib.hbm := hbm
dib.pBits := pBits
dib.width := nW
dib.height := nH
dib.bpp := bpp
dib.header := header
Return dib
}
startup()
{
global disposables
disposables := object()
disposables.pBitmaps := object()
disposables.hBitmaps := object()
If !(disposables.pToken := Gdip_Startup())
{
MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system
ExitApp
}
OnExit, gdipExit
}
gdipExit:
loop % disposables.hBitmaps._maxindex()
DllCall("DeleteObject", "Uint", disposables.hBitmaps[A_Index])
Gdip_Shutdown(disposables.pToken)
ExitApp
getPixels(imageFile)
{
global disposables
pBitmapFile1 := Gdip_CreateBitmapFromFile(imageFile)
hbmi := Gdip_CreateHBITMAPFromBitmap(pBitmapFile1)
width := Gdip_GetImageWidth(pBitmapFile1)
height := Gdip_GetImageHeight(pBitmapFile1)
mDCo := DllCall("CreateCompatibleDC", "Uint", 0)
mDCi := DllCall("CreateCompatibleDC", "Uint", 0)
dibSection := CreateDIBSection2(mDCo, width, height)
hBMo := dibSection.hbm
oBM := DllCall("SelectObject", "Uint", mDCo, "Uint", hBMo)
iBM := DllCall("SelectObject", "Uint", mDCi, "Uint", hbmi)
DllCall("BitBlt", "Uint", mDCo, "int", 0, "int", 0, "int", width, "int", height, "Uint", mDCi, "int", 0, "int", 0, "Uint", 0x40000000 | 0x00CC0020)
DllCall("SelectObject", "Uint", mDCo, "Uint", oBM)
DllCall("DeleteDC", "Uint", 0, "Uint", mDCi)
DllCall("DeleteDC", "Uint", 0, "Uint", mDCo)
Gdip_DisposeImage(pBitmapFile1)
DllCall("DeleteObject", "Uint", hBMi)
disposables.hBitmaps._insert(hBMo)
return dibSection
}
#Include Gdip.ahk
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define RED_C 0
#define GREEN_C 1
#define BLUE_C 2
#define GET_PIXEL(IMG, X, Y) ((IMG)->buf[ (Y) * (IMG)->width + (X) ])
int main(int argc, char **argv)
{
image im1, im2;
double totalDiff = 0.0;
unsigned int x, y;
if ( argc < 3 )
{
fprintf(stderr, "usage:\n%s FILE1 FILE2\n", argv[0]);
exit(1);
}
im1 = read_image(argv[1]);
if ( im1 == NULL ) exit(1);
im2 = read_image(argv[2]);
if ( im2 == NULL ) { free_img(im1); exit(1); }
if ( (im1->width != im2->width) || (im1->height != im2->height) )
{
fprintf(stderr, "width/height of the images must match!\n");
} else {
for(x=0; x < im1->width; x++)
{
for(y=0; y < im1->width; y++)
{
totalDiff += fabs( GET_PIXEL(im1, x, y)[RED_C] - GET_PIXEL(im2, x, y)[RED_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[GREEN_C] - GET_PIXEL(im2, x, y)[GREEN_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[BLUE_C] - GET_PIXEL(im2, x, y)[BLUE_C] ) / 255.0;
}
}
printf("%lf\n", 100.0 * totalDiff / (double)(im1->width * im1->height * 3) );
}
free_img(im1);
free_img(im2);
}
|
Convert this AutoHotKey snippet to C# and keep its semantics consistent. | startup()
dibSection := getPixels("lenna100.jpg")
dibSection2 := getPixels("lenna50.jpg")
pixels := dibSection.pBits
pixels2 := dibSection2.pBits
z := 0
loop % dibSection.width * dibSection.height * 4
{
x := numget(pixels - 1, A_Index, "uchar")
y := numget(pixels2 - 1, A_Index, "uchar")
z += abs(y - x)
}
msgbox % z / (dibSection.width * dibSection.height * 3 * 255 / 100 )
return
CreateDIBSection2(hDC, nW, nH, bpp = 32, ByRef pBits = "")
{
dib := object()
NumPut(VarSetCapacity(bi, 40, 0), bi)
NumPut(nW, bi, 4)
NumPut(nH, bi, 8)
NumPut(bpp, NumPut(1, bi, 12, "UShort"), 0, "Ushort")
NumPut(0, bi,16)
hbm := DllCall("gdi32\CreateDIBSection", "Uint", hDC, "Uint", &bi, "Uint", 0, "UintP", pBits, "Uint", 0, "Uint", 0)
dib.hbm := hbm
dib.pBits := pBits
dib.width := nW
dib.height := nH
dib.bpp := bpp
dib.header := header
Return dib
}
startup()
{
global disposables
disposables := object()
disposables.pBitmaps := object()
disposables.hBitmaps := object()
If !(disposables.pToken := Gdip_Startup())
{
MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system
ExitApp
}
OnExit, gdipExit
}
gdipExit:
loop % disposables.hBitmaps._maxindex()
DllCall("DeleteObject", "Uint", disposables.hBitmaps[A_Index])
Gdip_Shutdown(disposables.pToken)
ExitApp
getPixels(imageFile)
{
global disposables
pBitmapFile1 := Gdip_CreateBitmapFromFile(imageFile)
hbmi := Gdip_CreateHBITMAPFromBitmap(pBitmapFile1)
width := Gdip_GetImageWidth(pBitmapFile1)
height := Gdip_GetImageHeight(pBitmapFile1)
mDCo := DllCall("CreateCompatibleDC", "Uint", 0)
mDCi := DllCall("CreateCompatibleDC", "Uint", 0)
dibSection := CreateDIBSection2(mDCo, width, height)
hBMo := dibSection.hbm
oBM := DllCall("SelectObject", "Uint", mDCo, "Uint", hBMo)
iBM := DllCall("SelectObject", "Uint", mDCi, "Uint", hbmi)
DllCall("BitBlt", "Uint", mDCo, "int", 0, "int", 0, "int", width, "int", height, "Uint", mDCi, "int", 0, "int", 0, "Uint", 0x40000000 | 0x00CC0020)
DllCall("SelectObject", "Uint", mDCo, "Uint", oBM)
DllCall("DeleteDC", "Uint", 0, "Uint", mDCi)
DllCall("DeleteDC", "Uint", 0, "Uint", mDCo)
Gdip_DisposeImage(pBitmapFile1)
DllCall("DeleteObject", "Uint", hBMi)
disposables.hBitmaps._insert(hBMo)
return dibSection
}
#Include Gdip.ahk
| using System;
using System.Drawing;
class Program
{
static void Main()
{
Bitmap img1 = new Bitmap("Lenna50.jpg");
Bitmap img2 = new Bitmap("Lenna100.jpg");
if (img1.Size != img2.Size)
{
Console.Error.WriteLine("Images are of different sizes");
return;
}
float diff = 0;
for (int y = 0; y < img1.Height; y++)
{
for (int x = 0; x < img1.Width; x++)
{
Color pixel1 = img1.GetPixel(x, y);
Color pixel2 = img2.GetPixel(x, y);
diff += Math.Abs(pixel1.R - pixel2.R);
diff += Math.Abs(pixel1.G - pixel2.G);
diff += Math.Abs(pixel1.B - pixel2.B);
}
}
Console.WriteLine("diff: {0} %", 100 * (diff / 255) / (img1.Width * img1.Height * 3));
}
}
|
Can you help me rewrite this code in C++ instead of AutoHotKey, keeping it the same logically? | startup()
dibSection := getPixels("lenna100.jpg")
dibSection2 := getPixels("lenna50.jpg")
pixels := dibSection.pBits
pixels2 := dibSection2.pBits
z := 0
loop % dibSection.width * dibSection.height * 4
{
x := numget(pixels - 1, A_Index, "uchar")
y := numget(pixels2 - 1, A_Index, "uchar")
z += abs(y - x)
}
msgbox % z / (dibSection.width * dibSection.height * 3 * 255 / 100 )
return
CreateDIBSection2(hDC, nW, nH, bpp = 32, ByRef pBits = "")
{
dib := object()
NumPut(VarSetCapacity(bi, 40, 0), bi)
NumPut(nW, bi, 4)
NumPut(nH, bi, 8)
NumPut(bpp, NumPut(1, bi, 12, "UShort"), 0, "Ushort")
NumPut(0, bi,16)
hbm := DllCall("gdi32\CreateDIBSection", "Uint", hDC, "Uint", &bi, "Uint", 0, "UintP", pBits, "Uint", 0, "Uint", 0)
dib.hbm := hbm
dib.pBits := pBits
dib.width := nW
dib.height := nH
dib.bpp := bpp
dib.header := header
Return dib
}
startup()
{
global disposables
disposables := object()
disposables.pBitmaps := object()
disposables.hBitmaps := object()
If !(disposables.pToken := Gdip_Startup())
{
MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system
ExitApp
}
OnExit, gdipExit
}
gdipExit:
loop % disposables.hBitmaps._maxindex()
DllCall("DeleteObject", "Uint", disposables.hBitmaps[A_Index])
Gdip_Shutdown(disposables.pToken)
ExitApp
getPixels(imageFile)
{
global disposables
pBitmapFile1 := Gdip_CreateBitmapFromFile(imageFile)
hbmi := Gdip_CreateHBITMAPFromBitmap(pBitmapFile1)
width := Gdip_GetImageWidth(pBitmapFile1)
height := Gdip_GetImageHeight(pBitmapFile1)
mDCo := DllCall("CreateCompatibleDC", "Uint", 0)
mDCi := DllCall("CreateCompatibleDC", "Uint", 0)
dibSection := CreateDIBSection2(mDCo, width, height)
hBMo := dibSection.hbm
oBM := DllCall("SelectObject", "Uint", mDCo, "Uint", hBMo)
iBM := DllCall("SelectObject", "Uint", mDCi, "Uint", hbmi)
DllCall("BitBlt", "Uint", mDCo, "int", 0, "int", 0, "int", width, "int", height, "Uint", mDCi, "int", 0, "int", 0, "Uint", 0x40000000 | 0x00CC0020)
DllCall("SelectObject", "Uint", mDCo, "Uint", oBM)
DllCall("DeleteDC", "Uint", 0, "Uint", mDCi)
DllCall("DeleteDC", "Uint", 0, "Uint", mDCo)
Gdip_DisposeImage(pBitmapFile1)
DllCall("DeleteObject", "Uint", hBMi)
disposables.hBitmaps._insert(hBMo)
return dibSection
}
#Include Gdip.ahk
| #include <QImage>
#include <cstdlib>
#include <QColor>
#include <iostream>
int main( int argc , char *argv[ ] ) {
if ( argc != 3 ) {
std::cout << "Call this with imagecompare <file of image 1>"
<< " <file of image 2>\n" ;
return 1 ;
}
QImage firstImage ( argv[ 1 ] ) ;
QImage secondImage ( argv[ 2 ] ) ;
double totaldiff = 0.0 ;
int h = firstImage.height( ) ;
int w = firstImage.width( ) ;
int hsecond = secondImage.height( ) ;
int wsecond = secondImage.width( ) ;
if ( w != wsecond || h != hsecond ) {
std::cerr << "Error, pictures must have identical dimensions!\n" ;
return 2 ;
}
for ( int y = 0 ; y < h ; y++ ) {
uint *firstLine = ( uint* )firstImage.scanLine( y ) ;
uint *secondLine = ( uint* )secondImage.scanLine( y ) ;
for ( int x = 0 ; x < w ; x++ ) {
uint pixelFirst = firstLine[ x ] ;
int rFirst = qRed( pixelFirst ) ;
int gFirst = qGreen( pixelFirst ) ;
int bFirst = qBlue( pixelFirst ) ;
uint pixelSecond = secondLine[ x ] ;
int rSecond = qRed( pixelSecond ) ;
int gSecond = qGreen( pixelSecond ) ;
int bSecond = qBlue( pixelSecond ) ;
totaldiff += std::abs( rFirst - rSecond ) / 255.0 ;
totaldiff += std::abs( gFirst - gSecond ) / 255.0 ;
totaldiff += std::abs( bFirst -bSecond ) / 255.0 ;
}
}
std::cout << "The difference of the two pictures is " <<
(totaldiff * 100) / (w * h * 3) << " % !\n" ;
return 0 ;
}
|
Port the following code from AutoHotKey to Java with equivalent syntax and logic. | startup()
dibSection := getPixels("lenna100.jpg")
dibSection2 := getPixels("lenna50.jpg")
pixels := dibSection.pBits
pixels2 := dibSection2.pBits
z := 0
loop % dibSection.width * dibSection.height * 4
{
x := numget(pixels - 1, A_Index, "uchar")
y := numget(pixels2 - 1, A_Index, "uchar")
z += abs(y - x)
}
msgbox % z / (dibSection.width * dibSection.height * 3 * 255 / 100 )
return
CreateDIBSection2(hDC, nW, nH, bpp = 32, ByRef pBits = "")
{
dib := object()
NumPut(VarSetCapacity(bi, 40, 0), bi)
NumPut(nW, bi, 4)
NumPut(nH, bi, 8)
NumPut(bpp, NumPut(1, bi, 12, "UShort"), 0, "Ushort")
NumPut(0, bi,16)
hbm := DllCall("gdi32\CreateDIBSection", "Uint", hDC, "Uint", &bi, "Uint", 0, "UintP", pBits, "Uint", 0, "Uint", 0)
dib.hbm := hbm
dib.pBits := pBits
dib.width := nW
dib.height := nH
dib.bpp := bpp
dib.header := header
Return dib
}
startup()
{
global disposables
disposables := object()
disposables.pBitmaps := object()
disposables.hBitmaps := object()
If !(disposables.pToken := Gdip_Startup())
{
MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system
ExitApp
}
OnExit, gdipExit
}
gdipExit:
loop % disposables.hBitmaps._maxindex()
DllCall("DeleteObject", "Uint", disposables.hBitmaps[A_Index])
Gdip_Shutdown(disposables.pToken)
ExitApp
getPixels(imageFile)
{
global disposables
pBitmapFile1 := Gdip_CreateBitmapFromFile(imageFile)
hbmi := Gdip_CreateHBITMAPFromBitmap(pBitmapFile1)
width := Gdip_GetImageWidth(pBitmapFile1)
height := Gdip_GetImageHeight(pBitmapFile1)
mDCo := DllCall("CreateCompatibleDC", "Uint", 0)
mDCi := DllCall("CreateCompatibleDC", "Uint", 0)
dibSection := CreateDIBSection2(mDCo, width, height)
hBMo := dibSection.hbm
oBM := DllCall("SelectObject", "Uint", mDCo, "Uint", hBMo)
iBM := DllCall("SelectObject", "Uint", mDCi, "Uint", hbmi)
DllCall("BitBlt", "Uint", mDCo, "int", 0, "int", 0, "int", width, "int", height, "Uint", mDCi, "int", 0, "int", 0, "Uint", 0x40000000 | 0x00CC0020)
DllCall("SelectObject", "Uint", mDCo, "Uint", oBM)
DllCall("DeleteDC", "Uint", 0, "Uint", mDCi)
DllCall("DeleteDC", "Uint", 0, "Uint", mDCo)
Gdip_DisposeImage(pBitmapFile1)
DllCall("DeleteObject", "Uint", hBMi)
disposables.hBitmaps._insert(hBMo)
return dibSection
}
#Include Gdip.ahk
| import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public enum ImgDiffPercent {
;
public static void main(String[] args) throws IOException {
BufferedImage img1 = ImageIO.read(new File("Lenna50.jpg"));
BufferedImage img2 = ImageIO.read(new File("Lenna100.jpg"));
double p = getDifferencePercent(img1, img2);
System.out.println("diff percent: " + p);
}
private static double getDifferencePercent(BufferedImage img1, BufferedImage img2) {
int width = img1.getWidth();
int height = img1.getHeight();
int width2 = img2.getWidth();
int height2 = img2.getHeight();
if (width != width2 || height != height2) {
throw new IllegalArgumentException(String.format("Images must have the same dimensions: (%d,%d) vs. (%d,%d)", width, height, width2, height2));
}
long diff = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
diff += pixelDiff(img1.getRGB(x, y), img2.getRGB(x, y));
}
}
long maxDiff = 3L * 255 * width * height;
return 100.0 * diff / maxDiff;
}
private static int pixelDiff(int rgb1, int rgb2) {
int r1 = (rgb1 >> 16) & 0xff;
int g1 = (rgb1 >> 8) & 0xff;
int b1 = rgb1 & 0xff;
int r2 = (rgb2 >> 16) & 0xff;
int g2 = (rgb2 >> 8) & 0xff;
int b2 = rgb2 & 0xff;
return Math.abs(r1 - r2) + Math.abs(g1 - g2) + Math.abs(b1 - b2);
}
}
|
Generate an equivalent Python version of this AutoHotKey code. | startup()
dibSection := getPixels("lenna100.jpg")
dibSection2 := getPixels("lenna50.jpg")
pixels := dibSection.pBits
pixels2 := dibSection2.pBits
z := 0
loop % dibSection.width * dibSection.height * 4
{
x := numget(pixels - 1, A_Index, "uchar")
y := numget(pixels2 - 1, A_Index, "uchar")
z += abs(y - x)
}
msgbox % z / (dibSection.width * dibSection.height * 3 * 255 / 100 )
return
CreateDIBSection2(hDC, nW, nH, bpp = 32, ByRef pBits = "")
{
dib := object()
NumPut(VarSetCapacity(bi, 40, 0), bi)
NumPut(nW, bi, 4)
NumPut(nH, bi, 8)
NumPut(bpp, NumPut(1, bi, 12, "UShort"), 0, "Ushort")
NumPut(0, bi,16)
hbm := DllCall("gdi32\CreateDIBSection", "Uint", hDC, "Uint", &bi, "Uint", 0, "UintP", pBits, "Uint", 0, "Uint", 0)
dib.hbm := hbm
dib.pBits := pBits
dib.width := nW
dib.height := nH
dib.bpp := bpp
dib.header := header
Return dib
}
startup()
{
global disposables
disposables := object()
disposables.pBitmaps := object()
disposables.hBitmaps := object()
If !(disposables.pToken := Gdip_Startup())
{
MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system
ExitApp
}
OnExit, gdipExit
}
gdipExit:
loop % disposables.hBitmaps._maxindex()
DllCall("DeleteObject", "Uint", disposables.hBitmaps[A_Index])
Gdip_Shutdown(disposables.pToken)
ExitApp
getPixels(imageFile)
{
global disposables
pBitmapFile1 := Gdip_CreateBitmapFromFile(imageFile)
hbmi := Gdip_CreateHBITMAPFromBitmap(pBitmapFile1)
width := Gdip_GetImageWidth(pBitmapFile1)
height := Gdip_GetImageHeight(pBitmapFile1)
mDCo := DllCall("CreateCompatibleDC", "Uint", 0)
mDCi := DllCall("CreateCompatibleDC", "Uint", 0)
dibSection := CreateDIBSection2(mDCo, width, height)
hBMo := dibSection.hbm
oBM := DllCall("SelectObject", "Uint", mDCo, "Uint", hBMo)
iBM := DllCall("SelectObject", "Uint", mDCi, "Uint", hbmi)
DllCall("BitBlt", "Uint", mDCo, "int", 0, "int", 0, "int", width, "int", height, "Uint", mDCi, "int", 0, "int", 0, "Uint", 0x40000000 | 0x00CC0020)
DllCall("SelectObject", "Uint", mDCo, "Uint", oBM)
DllCall("DeleteDC", "Uint", 0, "Uint", mDCi)
DllCall("DeleteDC", "Uint", 0, "Uint", mDCo)
Gdip_DisposeImage(pBitmapFile1)
DllCall("DeleteObject", "Uint", hBMi)
disposables.hBitmaps._insert(hBMo)
return dibSection
}
#Include Gdip.ahk
| from PIL import Image
i1 = Image.open("image1.jpg")
i2 = Image.open("image2.jpg")
assert i1.mode == i2.mode, "Different kinds of images."
assert i1.size == i2.size, "Different sizes."
pairs = zip(i1.getdata(), i2.getdata())
if len(i1.getbands()) == 1:
dif = sum(abs(p1-p2) for p1,p2 in pairs)
else:
dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2))
ncomponents = i1.size[0] * i1.size[1] * 3
print ("Difference (percentage):", (dif / 255.0 * 100) / ncomponents)
|
Translate the given AutoHotKey code snippet into Go without altering its behavior. | startup()
dibSection := getPixels("lenna100.jpg")
dibSection2 := getPixels("lenna50.jpg")
pixels := dibSection.pBits
pixels2 := dibSection2.pBits
z := 0
loop % dibSection.width * dibSection.height * 4
{
x := numget(pixels - 1, A_Index, "uchar")
y := numget(pixels2 - 1, A_Index, "uchar")
z += abs(y - x)
}
msgbox % z / (dibSection.width * dibSection.height * 3 * 255 / 100 )
return
CreateDIBSection2(hDC, nW, nH, bpp = 32, ByRef pBits = "")
{
dib := object()
NumPut(VarSetCapacity(bi, 40, 0), bi)
NumPut(nW, bi, 4)
NumPut(nH, bi, 8)
NumPut(bpp, NumPut(1, bi, 12, "UShort"), 0, "Ushort")
NumPut(0, bi,16)
hbm := DllCall("gdi32\CreateDIBSection", "Uint", hDC, "Uint", &bi, "Uint", 0, "UintP", pBits, "Uint", 0, "Uint", 0)
dib.hbm := hbm
dib.pBits := pBits
dib.width := nW
dib.height := nH
dib.bpp := bpp
dib.header := header
Return dib
}
startup()
{
global disposables
disposables := object()
disposables.pBitmaps := object()
disposables.hBitmaps := object()
If !(disposables.pToken := Gdip_Startup())
{
MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system
ExitApp
}
OnExit, gdipExit
}
gdipExit:
loop % disposables.hBitmaps._maxindex()
DllCall("DeleteObject", "Uint", disposables.hBitmaps[A_Index])
Gdip_Shutdown(disposables.pToken)
ExitApp
getPixels(imageFile)
{
global disposables
pBitmapFile1 := Gdip_CreateBitmapFromFile(imageFile)
hbmi := Gdip_CreateHBITMAPFromBitmap(pBitmapFile1)
width := Gdip_GetImageWidth(pBitmapFile1)
height := Gdip_GetImageHeight(pBitmapFile1)
mDCo := DllCall("CreateCompatibleDC", "Uint", 0)
mDCi := DllCall("CreateCompatibleDC", "Uint", 0)
dibSection := CreateDIBSection2(mDCo, width, height)
hBMo := dibSection.hbm
oBM := DllCall("SelectObject", "Uint", mDCo, "Uint", hBMo)
iBM := DllCall("SelectObject", "Uint", mDCi, "Uint", hbmi)
DllCall("BitBlt", "Uint", mDCo, "int", 0, "int", 0, "int", width, "int", height, "Uint", mDCi, "int", 0, "int", 0, "Uint", 0x40000000 | 0x00CC0020)
DllCall("SelectObject", "Uint", mDCo, "Uint", oBM)
DllCall("DeleteDC", "Uint", 0, "Uint", mDCi)
DllCall("DeleteDC", "Uint", 0, "Uint", mDCo)
Gdip_DisposeImage(pBitmapFile1)
DllCall("DeleteObject", "Uint", hBMi)
disposables.hBitmaps._insert(hBMo)
return dibSection
}
#Include Gdip.ahk
| package main
import (
"fmt"
"image/jpeg"
"os"
"log"
"image"
)
func loadJpeg(filename string) (image.Image, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
img, err := jpeg.Decode(f)
if err != nil {
return nil, err
}
return img, nil
}
func diff(a, b uint32) int64 {
if a > b {
return int64(a - b)
}
return int64(b - a)
}
func main() {
i50, err := loadJpeg("Lenna50.jpg")
if err != nil {
log.Fatal(err)
}
i100, err := loadJpeg("Lenna100.jpg")
if err != nil {
log.Fatal(err)
}
if i50.ColorModel() != i100.ColorModel() {
log.Fatal("different color models")
}
b := i50.Bounds()
if !b.Eq(i100.Bounds()) {
log.Fatal("different image sizes")
}
var sum int64
for y := b.Min.Y; y < b.Max.Y; y++ {
for x := b.Min.X; x < b.Max.X; x++ {
r1, g1, b1, _ := i50.At(x, y).RGBA()
r2, g2, b2, _ := i100.At(x, y).RGBA()
sum += diff(r1, r2)
sum += diff(g1, g2)
sum += diff(b1, b2)
}
}
nPixels := (b.Max.X - b.Min.X) * (b.Max.Y - b.Min.Y)
fmt.Printf("Image difference: %f%%\n",
float64(sum*100)/(float64(nPixels)*0xffff*3))
}
|
Generate an equivalent C version of this BBC_Basic code. | hbm1% = FNloadimage("C:lenna50.jpg")
hbm2% = FNloadimage("C:lenna100.jpg")
SYS "CreateCompatibleDC", @memhdc% TO hdc1%
SYS "CreateCompatibleDC", @memhdc% TO hdc2%
SYS "SelectObject", hdc1%, hbm1%
SYS "SelectObject", hdc2%, hbm2%
diff% = 0
FOR y% = 0 TO 511
FOR x% = 0 TO 511
SYS "GetPixel", hdc1%, x%, y% TO rgb1%
SYS "GetPixel", hdc2%, x%, y% TO rgb2%
diff% += ABS((rgb1% AND &FF) - (rgb2% AND &FF))
diff% += ABS((rgb1% >> 8 AND &FF) - (rgb2% >> 8 AND &FF))
diff% += ABS((rgb1% >> 16) - (rgb2% >> 16))
NEXT
NEXT y%
PRINT "Image difference = "; 100 * diff% / 512^2 / 3 / 255 " %"
SYS "DeleteDC", hdc1%
SYS "DeleteDC", hdc2%
SYS "DeleteObject", hbm1%
SYS "DeleteObject", hbm2%
END
DEF FNloadimage(file$)
LOCAL iid{}, hbm%, pic%, ole%, olpp%, text%
DIM iid{a%,b%,c%,d%}, text% LOCAL 513
iid.a% = &7BF80980 :
iid.b% = &101ABF32
iid.c% = &AA00BB8B
iid.d% = &AB0C3000
SYS "MultiByteToWideChar", 0, 0, file$, -1, text%, 256
SYS "LoadLibrary", "OLEAUT32.DLL" TO ole%
SYS "GetProcAddress", ole%, "OleLoadPicturePath" TO olpp%
IF olpp%=0 THEN = 0
SYS olpp%, text%, 0, 0, 0, iid{}, ^pic% :
IF pic%=0 THEN = 0
SYS !(!pic%+12), pic%, ^hbm% :
SYS "FreeLibrary", ole%
= hbm%
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define RED_C 0
#define GREEN_C 1
#define BLUE_C 2
#define GET_PIXEL(IMG, X, Y) ((IMG)->buf[ (Y) * (IMG)->width + (X) ])
int main(int argc, char **argv)
{
image im1, im2;
double totalDiff = 0.0;
unsigned int x, y;
if ( argc < 3 )
{
fprintf(stderr, "usage:\n%s FILE1 FILE2\n", argv[0]);
exit(1);
}
im1 = read_image(argv[1]);
if ( im1 == NULL ) exit(1);
im2 = read_image(argv[2]);
if ( im2 == NULL ) { free_img(im1); exit(1); }
if ( (im1->width != im2->width) || (im1->height != im2->height) )
{
fprintf(stderr, "width/height of the images must match!\n");
} else {
for(x=0; x < im1->width; x++)
{
for(y=0; y < im1->width; y++)
{
totalDiff += fabs( GET_PIXEL(im1, x, y)[RED_C] - GET_PIXEL(im2, x, y)[RED_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[GREEN_C] - GET_PIXEL(im2, x, y)[GREEN_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[BLUE_C] - GET_PIXEL(im2, x, y)[BLUE_C] ) / 255.0;
}
}
printf("%lf\n", 100.0 * totalDiff / (double)(im1->width * im1->height * 3) );
}
free_img(im1);
free_img(im2);
}
|
Convert this BBC_Basic block to C#, preserving its control flow and logic. | hbm1% = FNloadimage("C:lenna50.jpg")
hbm2% = FNloadimage("C:lenna100.jpg")
SYS "CreateCompatibleDC", @memhdc% TO hdc1%
SYS "CreateCompatibleDC", @memhdc% TO hdc2%
SYS "SelectObject", hdc1%, hbm1%
SYS "SelectObject", hdc2%, hbm2%
diff% = 0
FOR y% = 0 TO 511
FOR x% = 0 TO 511
SYS "GetPixel", hdc1%, x%, y% TO rgb1%
SYS "GetPixel", hdc2%, x%, y% TO rgb2%
diff% += ABS((rgb1% AND &FF) - (rgb2% AND &FF))
diff% += ABS((rgb1% >> 8 AND &FF) - (rgb2% >> 8 AND &FF))
diff% += ABS((rgb1% >> 16) - (rgb2% >> 16))
NEXT
NEXT y%
PRINT "Image difference = "; 100 * diff% / 512^2 / 3 / 255 " %"
SYS "DeleteDC", hdc1%
SYS "DeleteDC", hdc2%
SYS "DeleteObject", hbm1%
SYS "DeleteObject", hbm2%
END
DEF FNloadimage(file$)
LOCAL iid{}, hbm%, pic%, ole%, olpp%, text%
DIM iid{a%,b%,c%,d%}, text% LOCAL 513
iid.a% = &7BF80980 :
iid.b% = &101ABF32
iid.c% = &AA00BB8B
iid.d% = &AB0C3000
SYS "MultiByteToWideChar", 0, 0, file$, -1, text%, 256
SYS "LoadLibrary", "OLEAUT32.DLL" TO ole%
SYS "GetProcAddress", ole%, "OleLoadPicturePath" TO olpp%
IF olpp%=0 THEN = 0
SYS olpp%, text%, 0, 0, 0, iid{}, ^pic% :
IF pic%=0 THEN = 0
SYS !(!pic%+12), pic%, ^hbm% :
SYS "FreeLibrary", ole%
= hbm%
| using System;
using System.Drawing;
class Program
{
static void Main()
{
Bitmap img1 = new Bitmap("Lenna50.jpg");
Bitmap img2 = new Bitmap("Lenna100.jpg");
if (img1.Size != img2.Size)
{
Console.Error.WriteLine("Images are of different sizes");
return;
}
float diff = 0;
for (int y = 0; y < img1.Height; y++)
{
for (int x = 0; x < img1.Width; x++)
{
Color pixel1 = img1.GetPixel(x, y);
Color pixel2 = img2.GetPixel(x, y);
diff += Math.Abs(pixel1.R - pixel2.R);
diff += Math.Abs(pixel1.G - pixel2.G);
diff += Math.Abs(pixel1.B - pixel2.B);
}
}
Console.WriteLine("diff: {0} %", 100 * (diff / 255) / (img1.Width * img1.Height * 3));
}
}
|
Please provide an equivalent version of this BBC_Basic code in C++. | hbm1% = FNloadimage("C:lenna50.jpg")
hbm2% = FNloadimage("C:lenna100.jpg")
SYS "CreateCompatibleDC", @memhdc% TO hdc1%
SYS "CreateCompatibleDC", @memhdc% TO hdc2%
SYS "SelectObject", hdc1%, hbm1%
SYS "SelectObject", hdc2%, hbm2%
diff% = 0
FOR y% = 0 TO 511
FOR x% = 0 TO 511
SYS "GetPixel", hdc1%, x%, y% TO rgb1%
SYS "GetPixel", hdc2%, x%, y% TO rgb2%
diff% += ABS((rgb1% AND &FF) - (rgb2% AND &FF))
diff% += ABS((rgb1% >> 8 AND &FF) - (rgb2% >> 8 AND &FF))
diff% += ABS((rgb1% >> 16) - (rgb2% >> 16))
NEXT
NEXT y%
PRINT "Image difference = "; 100 * diff% / 512^2 / 3 / 255 " %"
SYS "DeleteDC", hdc1%
SYS "DeleteDC", hdc2%
SYS "DeleteObject", hbm1%
SYS "DeleteObject", hbm2%
END
DEF FNloadimage(file$)
LOCAL iid{}, hbm%, pic%, ole%, olpp%, text%
DIM iid{a%,b%,c%,d%}, text% LOCAL 513
iid.a% = &7BF80980 :
iid.b% = &101ABF32
iid.c% = &AA00BB8B
iid.d% = &AB0C3000
SYS "MultiByteToWideChar", 0, 0, file$, -1, text%, 256
SYS "LoadLibrary", "OLEAUT32.DLL" TO ole%
SYS "GetProcAddress", ole%, "OleLoadPicturePath" TO olpp%
IF olpp%=0 THEN = 0
SYS olpp%, text%, 0, 0, 0, iid{}, ^pic% :
IF pic%=0 THEN = 0
SYS !(!pic%+12), pic%, ^hbm% :
SYS "FreeLibrary", ole%
= hbm%
| #include <QImage>
#include <cstdlib>
#include <QColor>
#include <iostream>
int main( int argc , char *argv[ ] ) {
if ( argc != 3 ) {
std::cout << "Call this with imagecompare <file of image 1>"
<< " <file of image 2>\n" ;
return 1 ;
}
QImage firstImage ( argv[ 1 ] ) ;
QImage secondImage ( argv[ 2 ] ) ;
double totaldiff = 0.0 ;
int h = firstImage.height( ) ;
int w = firstImage.width( ) ;
int hsecond = secondImage.height( ) ;
int wsecond = secondImage.width( ) ;
if ( w != wsecond || h != hsecond ) {
std::cerr << "Error, pictures must have identical dimensions!\n" ;
return 2 ;
}
for ( int y = 0 ; y < h ; y++ ) {
uint *firstLine = ( uint* )firstImage.scanLine( y ) ;
uint *secondLine = ( uint* )secondImage.scanLine( y ) ;
for ( int x = 0 ; x < w ; x++ ) {
uint pixelFirst = firstLine[ x ] ;
int rFirst = qRed( pixelFirst ) ;
int gFirst = qGreen( pixelFirst ) ;
int bFirst = qBlue( pixelFirst ) ;
uint pixelSecond = secondLine[ x ] ;
int rSecond = qRed( pixelSecond ) ;
int gSecond = qGreen( pixelSecond ) ;
int bSecond = qBlue( pixelSecond ) ;
totaldiff += std::abs( rFirst - rSecond ) / 255.0 ;
totaldiff += std::abs( gFirst - gSecond ) / 255.0 ;
totaldiff += std::abs( bFirst -bSecond ) / 255.0 ;
}
}
std::cout << "The difference of the two pictures is " <<
(totaldiff * 100) / (w * h * 3) << " % !\n" ;
return 0 ;
}
|
Convert the following code from BBC_Basic to Java, ensuring the logic remains intact. | hbm1% = FNloadimage("C:lenna50.jpg")
hbm2% = FNloadimage("C:lenna100.jpg")
SYS "CreateCompatibleDC", @memhdc% TO hdc1%
SYS "CreateCompatibleDC", @memhdc% TO hdc2%
SYS "SelectObject", hdc1%, hbm1%
SYS "SelectObject", hdc2%, hbm2%
diff% = 0
FOR y% = 0 TO 511
FOR x% = 0 TO 511
SYS "GetPixel", hdc1%, x%, y% TO rgb1%
SYS "GetPixel", hdc2%, x%, y% TO rgb2%
diff% += ABS((rgb1% AND &FF) - (rgb2% AND &FF))
diff% += ABS((rgb1% >> 8 AND &FF) - (rgb2% >> 8 AND &FF))
diff% += ABS((rgb1% >> 16) - (rgb2% >> 16))
NEXT
NEXT y%
PRINT "Image difference = "; 100 * diff% / 512^2 / 3 / 255 " %"
SYS "DeleteDC", hdc1%
SYS "DeleteDC", hdc2%
SYS "DeleteObject", hbm1%
SYS "DeleteObject", hbm2%
END
DEF FNloadimage(file$)
LOCAL iid{}, hbm%, pic%, ole%, olpp%, text%
DIM iid{a%,b%,c%,d%}, text% LOCAL 513
iid.a% = &7BF80980 :
iid.b% = &101ABF32
iid.c% = &AA00BB8B
iid.d% = &AB0C3000
SYS "MultiByteToWideChar", 0, 0, file$, -1, text%, 256
SYS "LoadLibrary", "OLEAUT32.DLL" TO ole%
SYS "GetProcAddress", ole%, "OleLoadPicturePath" TO olpp%
IF olpp%=0 THEN = 0
SYS olpp%, text%, 0, 0, 0, iid{}, ^pic% :
IF pic%=0 THEN = 0
SYS !(!pic%+12), pic%, ^hbm% :
SYS "FreeLibrary", ole%
= hbm%
| import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public enum ImgDiffPercent {
;
public static void main(String[] args) throws IOException {
BufferedImage img1 = ImageIO.read(new File("Lenna50.jpg"));
BufferedImage img2 = ImageIO.read(new File("Lenna100.jpg"));
double p = getDifferencePercent(img1, img2);
System.out.println("diff percent: " + p);
}
private static double getDifferencePercent(BufferedImage img1, BufferedImage img2) {
int width = img1.getWidth();
int height = img1.getHeight();
int width2 = img2.getWidth();
int height2 = img2.getHeight();
if (width != width2 || height != height2) {
throw new IllegalArgumentException(String.format("Images must have the same dimensions: (%d,%d) vs. (%d,%d)", width, height, width2, height2));
}
long diff = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
diff += pixelDiff(img1.getRGB(x, y), img2.getRGB(x, y));
}
}
long maxDiff = 3L * 255 * width * height;
return 100.0 * diff / maxDiff;
}
private static int pixelDiff(int rgb1, int rgb2) {
int r1 = (rgb1 >> 16) & 0xff;
int g1 = (rgb1 >> 8) & 0xff;
int b1 = rgb1 & 0xff;
int r2 = (rgb2 >> 16) & 0xff;
int g2 = (rgb2 >> 8) & 0xff;
int b2 = rgb2 & 0xff;
return Math.abs(r1 - r2) + Math.abs(g1 - g2) + Math.abs(b1 - b2);
}
}
|
Change the programming language of this snippet from BBC_Basic to Python without modifying what it does. | hbm1% = FNloadimage("C:lenna50.jpg")
hbm2% = FNloadimage("C:lenna100.jpg")
SYS "CreateCompatibleDC", @memhdc% TO hdc1%
SYS "CreateCompatibleDC", @memhdc% TO hdc2%
SYS "SelectObject", hdc1%, hbm1%
SYS "SelectObject", hdc2%, hbm2%
diff% = 0
FOR y% = 0 TO 511
FOR x% = 0 TO 511
SYS "GetPixel", hdc1%, x%, y% TO rgb1%
SYS "GetPixel", hdc2%, x%, y% TO rgb2%
diff% += ABS((rgb1% AND &FF) - (rgb2% AND &FF))
diff% += ABS((rgb1% >> 8 AND &FF) - (rgb2% >> 8 AND &FF))
diff% += ABS((rgb1% >> 16) - (rgb2% >> 16))
NEXT
NEXT y%
PRINT "Image difference = "; 100 * diff% / 512^2 / 3 / 255 " %"
SYS "DeleteDC", hdc1%
SYS "DeleteDC", hdc2%
SYS "DeleteObject", hbm1%
SYS "DeleteObject", hbm2%
END
DEF FNloadimage(file$)
LOCAL iid{}, hbm%, pic%, ole%, olpp%, text%
DIM iid{a%,b%,c%,d%}, text% LOCAL 513
iid.a% = &7BF80980 :
iid.b% = &101ABF32
iid.c% = &AA00BB8B
iid.d% = &AB0C3000
SYS "MultiByteToWideChar", 0, 0, file$, -1, text%, 256
SYS "LoadLibrary", "OLEAUT32.DLL" TO ole%
SYS "GetProcAddress", ole%, "OleLoadPicturePath" TO olpp%
IF olpp%=0 THEN = 0
SYS olpp%, text%, 0, 0, 0, iid{}, ^pic% :
IF pic%=0 THEN = 0
SYS !(!pic%+12), pic%, ^hbm% :
SYS "FreeLibrary", ole%
= hbm%
| from PIL import Image
i1 = Image.open("image1.jpg")
i2 = Image.open("image2.jpg")
assert i1.mode == i2.mode, "Different kinds of images."
assert i1.size == i2.size, "Different sizes."
pairs = zip(i1.getdata(), i2.getdata())
if len(i1.getbands()) == 1:
dif = sum(abs(p1-p2) for p1,p2 in pairs)
else:
dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2))
ncomponents = i1.size[0] * i1.size[1] * 3
print ("Difference (percentage):", (dif / 255.0 * 100) / ncomponents)
|
Translate this program into Go but keep the logic exactly as in BBC_Basic. | hbm1% = FNloadimage("C:lenna50.jpg")
hbm2% = FNloadimage("C:lenna100.jpg")
SYS "CreateCompatibleDC", @memhdc% TO hdc1%
SYS "CreateCompatibleDC", @memhdc% TO hdc2%
SYS "SelectObject", hdc1%, hbm1%
SYS "SelectObject", hdc2%, hbm2%
diff% = 0
FOR y% = 0 TO 511
FOR x% = 0 TO 511
SYS "GetPixel", hdc1%, x%, y% TO rgb1%
SYS "GetPixel", hdc2%, x%, y% TO rgb2%
diff% += ABS((rgb1% AND &FF) - (rgb2% AND &FF))
diff% += ABS((rgb1% >> 8 AND &FF) - (rgb2% >> 8 AND &FF))
diff% += ABS((rgb1% >> 16) - (rgb2% >> 16))
NEXT
NEXT y%
PRINT "Image difference = "; 100 * diff% / 512^2 / 3 / 255 " %"
SYS "DeleteDC", hdc1%
SYS "DeleteDC", hdc2%
SYS "DeleteObject", hbm1%
SYS "DeleteObject", hbm2%
END
DEF FNloadimage(file$)
LOCAL iid{}, hbm%, pic%, ole%, olpp%, text%
DIM iid{a%,b%,c%,d%}, text% LOCAL 513
iid.a% = &7BF80980 :
iid.b% = &101ABF32
iid.c% = &AA00BB8B
iid.d% = &AB0C3000
SYS "MultiByteToWideChar", 0, 0, file$, -1, text%, 256
SYS "LoadLibrary", "OLEAUT32.DLL" TO ole%
SYS "GetProcAddress", ole%, "OleLoadPicturePath" TO olpp%
IF olpp%=0 THEN = 0
SYS olpp%, text%, 0, 0, 0, iid{}, ^pic% :
IF pic%=0 THEN = 0
SYS !(!pic%+12), pic%, ^hbm% :
SYS "FreeLibrary", ole%
= hbm%
| package main
import (
"fmt"
"image/jpeg"
"os"
"log"
"image"
)
func loadJpeg(filename string) (image.Image, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
img, err := jpeg.Decode(f)
if err != nil {
return nil, err
}
return img, nil
}
func diff(a, b uint32) int64 {
if a > b {
return int64(a - b)
}
return int64(b - a)
}
func main() {
i50, err := loadJpeg("Lenna50.jpg")
if err != nil {
log.Fatal(err)
}
i100, err := loadJpeg("Lenna100.jpg")
if err != nil {
log.Fatal(err)
}
if i50.ColorModel() != i100.ColorModel() {
log.Fatal("different color models")
}
b := i50.Bounds()
if !b.Eq(i100.Bounds()) {
log.Fatal("different image sizes")
}
var sum int64
for y := b.Min.Y; y < b.Max.Y; y++ {
for x := b.Min.X; x < b.Max.X; x++ {
r1, g1, b1, _ := i50.At(x, y).RGBA()
r2, g2, b2, _ := i100.At(x, y).RGBA()
sum += diff(r1, r2)
sum += diff(g1, g2)
sum += diff(b1, b2)
}
}
nPixels := (b.Max.X - b.Min.X) * (b.Max.Y - b.Min.Y)
fmt.Printf("Image difference: %f%%\n",
float64(sum*100)/(float64(nPixels)*0xffff*3))
}
|
Please provide an equivalent version of this Common_Lisp code in C. | (require 'cl-jpeg)
(defun compare-images (file1 file2)
(declare (optimize (speed 3) (safety 0) (debug 0)))
(multiple-value-bind (image1 height width) (jpeg:decode-image file1)
(let ((image2 (jpeg:decode-image file2)))
(loop for i of-type (unsigned-byte 8) across (the simple-vector image1)
for j of-type (unsigned-byte 8) across (the simple-vector image2)
sum (the fixnum (abs (- i j))) into difference of-type fixnum
finally (return (coerce (/ difference width height #.(* 3 255))
'double-float))))))
CL-USER> (* 100 (compare-images "Lenna50.jpg" "Lenna100.jpg"))
1.774856467652165d0
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define RED_C 0
#define GREEN_C 1
#define BLUE_C 2
#define GET_PIXEL(IMG, X, Y) ((IMG)->buf[ (Y) * (IMG)->width + (X) ])
int main(int argc, char **argv)
{
image im1, im2;
double totalDiff = 0.0;
unsigned int x, y;
if ( argc < 3 )
{
fprintf(stderr, "usage:\n%s FILE1 FILE2\n", argv[0]);
exit(1);
}
im1 = read_image(argv[1]);
if ( im1 == NULL ) exit(1);
im2 = read_image(argv[2]);
if ( im2 == NULL ) { free_img(im1); exit(1); }
if ( (im1->width != im2->width) || (im1->height != im2->height) )
{
fprintf(stderr, "width/height of the images must match!\n");
} else {
for(x=0; x < im1->width; x++)
{
for(y=0; y < im1->width; y++)
{
totalDiff += fabs( GET_PIXEL(im1, x, y)[RED_C] - GET_PIXEL(im2, x, y)[RED_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[GREEN_C] - GET_PIXEL(im2, x, y)[GREEN_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[BLUE_C] - GET_PIXEL(im2, x, y)[BLUE_C] ) / 255.0;
}
}
printf("%lf\n", 100.0 * totalDiff / (double)(im1->width * im1->height * 3) );
}
free_img(im1);
free_img(im2);
}
|
Rewrite the snippet below in C# so it works the same as the original Common_Lisp code. | (require 'cl-jpeg)
(defun compare-images (file1 file2)
(declare (optimize (speed 3) (safety 0) (debug 0)))
(multiple-value-bind (image1 height width) (jpeg:decode-image file1)
(let ((image2 (jpeg:decode-image file2)))
(loop for i of-type (unsigned-byte 8) across (the simple-vector image1)
for j of-type (unsigned-byte 8) across (the simple-vector image2)
sum (the fixnum (abs (- i j))) into difference of-type fixnum
finally (return (coerce (/ difference width height #.(* 3 255))
'double-float))))))
CL-USER> (* 100 (compare-images "Lenna50.jpg" "Lenna100.jpg"))
1.774856467652165d0
| using System;
using System.Drawing;
class Program
{
static void Main()
{
Bitmap img1 = new Bitmap("Lenna50.jpg");
Bitmap img2 = new Bitmap("Lenna100.jpg");
if (img1.Size != img2.Size)
{
Console.Error.WriteLine("Images are of different sizes");
return;
}
float diff = 0;
for (int y = 0; y < img1.Height; y++)
{
for (int x = 0; x < img1.Width; x++)
{
Color pixel1 = img1.GetPixel(x, y);
Color pixel2 = img2.GetPixel(x, y);
diff += Math.Abs(pixel1.R - pixel2.R);
diff += Math.Abs(pixel1.G - pixel2.G);
diff += Math.Abs(pixel1.B - pixel2.B);
}
}
Console.WriteLine("diff: {0} %", 100 * (diff / 255) / (img1.Width * img1.Height * 3));
}
}
|
Maintain the same structure and functionality when rewriting this code in C++. | (require 'cl-jpeg)
(defun compare-images (file1 file2)
(declare (optimize (speed 3) (safety 0) (debug 0)))
(multiple-value-bind (image1 height width) (jpeg:decode-image file1)
(let ((image2 (jpeg:decode-image file2)))
(loop for i of-type (unsigned-byte 8) across (the simple-vector image1)
for j of-type (unsigned-byte 8) across (the simple-vector image2)
sum (the fixnum (abs (- i j))) into difference of-type fixnum
finally (return (coerce (/ difference width height #.(* 3 255))
'double-float))))))
CL-USER> (* 100 (compare-images "Lenna50.jpg" "Lenna100.jpg"))
1.774856467652165d0
| #include <QImage>
#include <cstdlib>
#include <QColor>
#include <iostream>
int main( int argc , char *argv[ ] ) {
if ( argc != 3 ) {
std::cout << "Call this with imagecompare <file of image 1>"
<< " <file of image 2>\n" ;
return 1 ;
}
QImage firstImage ( argv[ 1 ] ) ;
QImage secondImage ( argv[ 2 ] ) ;
double totaldiff = 0.0 ;
int h = firstImage.height( ) ;
int w = firstImage.width( ) ;
int hsecond = secondImage.height( ) ;
int wsecond = secondImage.width( ) ;
if ( w != wsecond || h != hsecond ) {
std::cerr << "Error, pictures must have identical dimensions!\n" ;
return 2 ;
}
for ( int y = 0 ; y < h ; y++ ) {
uint *firstLine = ( uint* )firstImage.scanLine( y ) ;
uint *secondLine = ( uint* )secondImage.scanLine( y ) ;
for ( int x = 0 ; x < w ; x++ ) {
uint pixelFirst = firstLine[ x ] ;
int rFirst = qRed( pixelFirst ) ;
int gFirst = qGreen( pixelFirst ) ;
int bFirst = qBlue( pixelFirst ) ;
uint pixelSecond = secondLine[ x ] ;
int rSecond = qRed( pixelSecond ) ;
int gSecond = qGreen( pixelSecond ) ;
int bSecond = qBlue( pixelSecond ) ;
totaldiff += std::abs( rFirst - rSecond ) / 255.0 ;
totaldiff += std::abs( gFirst - gSecond ) / 255.0 ;
totaldiff += std::abs( bFirst -bSecond ) / 255.0 ;
}
}
std::cout << "The difference of the two pictures is " <<
(totaldiff * 100) / (w * h * 3) << " % !\n" ;
return 0 ;
}
|
Port the provided Common_Lisp code into Java while preserving the original functionality. | (require 'cl-jpeg)
(defun compare-images (file1 file2)
(declare (optimize (speed 3) (safety 0) (debug 0)))
(multiple-value-bind (image1 height width) (jpeg:decode-image file1)
(let ((image2 (jpeg:decode-image file2)))
(loop for i of-type (unsigned-byte 8) across (the simple-vector image1)
for j of-type (unsigned-byte 8) across (the simple-vector image2)
sum (the fixnum (abs (- i j))) into difference of-type fixnum
finally (return (coerce (/ difference width height #.(* 3 255))
'double-float))))))
CL-USER> (* 100 (compare-images "Lenna50.jpg" "Lenna100.jpg"))
1.774856467652165d0
| import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public enum ImgDiffPercent {
;
public static void main(String[] args) throws IOException {
BufferedImage img1 = ImageIO.read(new File("Lenna50.jpg"));
BufferedImage img2 = ImageIO.read(new File("Lenna100.jpg"));
double p = getDifferencePercent(img1, img2);
System.out.println("diff percent: " + p);
}
private static double getDifferencePercent(BufferedImage img1, BufferedImage img2) {
int width = img1.getWidth();
int height = img1.getHeight();
int width2 = img2.getWidth();
int height2 = img2.getHeight();
if (width != width2 || height != height2) {
throw new IllegalArgumentException(String.format("Images must have the same dimensions: (%d,%d) vs. (%d,%d)", width, height, width2, height2));
}
long diff = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
diff += pixelDiff(img1.getRGB(x, y), img2.getRGB(x, y));
}
}
long maxDiff = 3L * 255 * width * height;
return 100.0 * diff / maxDiff;
}
private static int pixelDiff(int rgb1, int rgb2) {
int r1 = (rgb1 >> 16) & 0xff;
int g1 = (rgb1 >> 8) & 0xff;
int b1 = rgb1 & 0xff;
int r2 = (rgb2 >> 16) & 0xff;
int g2 = (rgb2 >> 8) & 0xff;
int b2 = rgb2 & 0xff;
return Math.abs(r1 - r2) + Math.abs(g1 - g2) + Math.abs(b1 - b2);
}
}
|
Preserve the algorithm and functionality while converting the code from Common_Lisp to Python. | (require 'cl-jpeg)
(defun compare-images (file1 file2)
(declare (optimize (speed 3) (safety 0) (debug 0)))
(multiple-value-bind (image1 height width) (jpeg:decode-image file1)
(let ((image2 (jpeg:decode-image file2)))
(loop for i of-type (unsigned-byte 8) across (the simple-vector image1)
for j of-type (unsigned-byte 8) across (the simple-vector image2)
sum (the fixnum (abs (- i j))) into difference of-type fixnum
finally (return (coerce (/ difference width height #.(* 3 255))
'double-float))))))
CL-USER> (* 100 (compare-images "Lenna50.jpg" "Lenna100.jpg"))
1.774856467652165d0
| from PIL import Image
i1 = Image.open("image1.jpg")
i2 = Image.open("image2.jpg")
assert i1.mode == i2.mode, "Different kinds of images."
assert i1.size == i2.size, "Different sizes."
pairs = zip(i1.getdata(), i2.getdata())
if len(i1.getbands()) == 1:
dif = sum(abs(p1-p2) for p1,p2 in pairs)
else:
dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2))
ncomponents = i1.size[0] * i1.size[1] * 3
print ("Difference (percentage):", (dif / 255.0 * 100) / ncomponents)
|
Port the following code from Common_Lisp to Go with equivalent syntax and logic. | (require 'cl-jpeg)
(defun compare-images (file1 file2)
(declare (optimize (speed 3) (safety 0) (debug 0)))
(multiple-value-bind (image1 height width) (jpeg:decode-image file1)
(let ((image2 (jpeg:decode-image file2)))
(loop for i of-type (unsigned-byte 8) across (the simple-vector image1)
for j of-type (unsigned-byte 8) across (the simple-vector image2)
sum (the fixnum (abs (- i j))) into difference of-type fixnum
finally (return (coerce (/ difference width height #.(* 3 255))
'double-float))))))
CL-USER> (* 100 (compare-images "Lenna50.jpg" "Lenna100.jpg"))
1.774856467652165d0
| package main
import (
"fmt"
"image/jpeg"
"os"
"log"
"image"
)
func loadJpeg(filename string) (image.Image, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
img, err := jpeg.Decode(f)
if err != nil {
return nil, err
}
return img, nil
}
func diff(a, b uint32) int64 {
if a > b {
return int64(a - b)
}
return int64(b - a)
}
func main() {
i50, err := loadJpeg("Lenna50.jpg")
if err != nil {
log.Fatal(err)
}
i100, err := loadJpeg("Lenna100.jpg")
if err != nil {
log.Fatal(err)
}
if i50.ColorModel() != i100.ColorModel() {
log.Fatal("different color models")
}
b := i50.Bounds()
if !b.Eq(i100.Bounds()) {
log.Fatal("different image sizes")
}
var sum int64
for y := b.Min.Y; y < b.Max.Y; y++ {
for x := b.Min.X; x < b.Max.X; x++ {
r1, g1, b1, _ := i50.At(x, y).RGBA()
r2, g2, b2, _ := i100.At(x, y).RGBA()
sum += diff(r1, r2)
sum += diff(g1, g2)
sum += diff(b1, b2)
}
}
nPixels := (b.Max.X - b.Min.X) * (b.Max.Y - b.Min.Y)
fmt.Printf("Image difference: %f%%\n",
float64(sum*100)/(float64(nPixels)*0xffff*3))
}
|
Generate a C translation of this D snippet without changing its computational steps. | import std.stdio, std.exception, std.range, std.math, bitmap;
void main() {
Image!RGB i1, i2;
i1 = i1.loadPPM6("Lenna50.ppm");
i2 = i2.loadPPM6("Lenna100.ppm");
enforce(i1.nx == i2.nx && i1.ny == i2.ny, "Different sizes.");
real dif = 0.0;
foreach (p, q; zip(i1.image, i2.image))
dif += abs(p.r - q.r) + abs(p.g - q.g) + abs(p.b - q.b);
immutable nData = i1.nx * i1.ny * 3;
writeln("Difference (percentage): ",
(dif / 255.0 * 100) / nData);
}
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define RED_C 0
#define GREEN_C 1
#define BLUE_C 2
#define GET_PIXEL(IMG, X, Y) ((IMG)->buf[ (Y) * (IMG)->width + (X) ])
int main(int argc, char **argv)
{
image im1, im2;
double totalDiff = 0.0;
unsigned int x, y;
if ( argc < 3 )
{
fprintf(stderr, "usage:\n%s FILE1 FILE2\n", argv[0]);
exit(1);
}
im1 = read_image(argv[1]);
if ( im1 == NULL ) exit(1);
im2 = read_image(argv[2]);
if ( im2 == NULL ) { free_img(im1); exit(1); }
if ( (im1->width != im2->width) || (im1->height != im2->height) )
{
fprintf(stderr, "width/height of the images must match!\n");
} else {
for(x=0; x < im1->width; x++)
{
for(y=0; y < im1->width; y++)
{
totalDiff += fabs( GET_PIXEL(im1, x, y)[RED_C] - GET_PIXEL(im2, x, y)[RED_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[GREEN_C] - GET_PIXEL(im2, x, y)[GREEN_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[BLUE_C] - GET_PIXEL(im2, x, y)[BLUE_C] ) / 255.0;
}
}
printf("%lf\n", 100.0 * totalDiff / (double)(im1->width * im1->height * 3) );
}
free_img(im1);
free_img(im2);
}
|
Convert this D block to C#, preserving its control flow and logic. | import std.stdio, std.exception, std.range, std.math, bitmap;
void main() {
Image!RGB i1, i2;
i1 = i1.loadPPM6("Lenna50.ppm");
i2 = i2.loadPPM6("Lenna100.ppm");
enforce(i1.nx == i2.nx && i1.ny == i2.ny, "Different sizes.");
real dif = 0.0;
foreach (p, q; zip(i1.image, i2.image))
dif += abs(p.r - q.r) + abs(p.g - q.g) + abs(p.b - q.b);
immutable nData = i1.nx * i1.ny * 3;
writeln("Difference (percentage): ",
(dif / 255.0 * 100) / nData);
}
| using System;
using System.Drawing;
class Program
{
static void Main()
{
Bitmap img1 = new Bitmap("Lenna50.jpg");
Bitmap img2 = new Bitmap("Lenna100.jpg");
if (img1.Size != img2.Size)
{
Console.Error.WriteLine("Images are of different sizes");
return;
}
float diff = 0;
for (int y = 0; y < img1.Height; y++)
{
for (int x = 0; x < img1.Width; x++)
{
Color pixel1 = img1.GetPixel(x, y);
Color pixel2 = img2.GetPixel(x, y);
diff += Math.Abs(pixel1.R - pixel2.R);
diff += Math.Abs(pixel1.G - pixel2.G);
diff += Math.Abs(pixel1.B - pixel2.B);
}
}
Console.WriteLine("diff: {0} %", 100 * (diff / 255) / (img1.Width * img1.Height * 3));
}
}
|
Generate an equivalent C++ version of this D code. | import std.stdio, std.exception, std.range, std.math, bitmap;
void main() {
Image!RGB i1, i2;
i1 = i1.loadPPM6("Lenna50.ppm");
i2 = i2.loadPPM6("Lenna100.ppm");
enforce(i1.nx == i2.nx && i1.ny == i2.ny, "Different sizes.");
real dif = 0.0;
foreach (p, q; zip(i1.image, i2.image))
dif += abs(p.r - q.r) + abs(p.g - q.g) + abs(p.b - q.b);
immutable nData = i1.nx * i1.ny * 3;
writeln("Difference (percentage): ",
(dif / 255.0 * 100) / nData);
}
| #include <QImage>
#include <cstdlib>
#include <QColor>
#include <iostream>
int main( int argc , char *argv[ ] ) {
if ( argc != 3 ) {
std::cout << "Call this with imagecompare <file of image 1>"
<< " <file of image 2>\n" ;
return 1 ;
}
QImage firstImage ( argv[ 1 ] ) ;
QImage secondImage ( argv[ 2 ] ) ;
double totaldiff = 0.0 ;
int h = firstImage.height( ) ;
int w = firstImage.width( ) ;
int hsecond = secondImage.height( ) ;
int wsecond = secondImage.width( ) ;
if ( w != wsecond || h != hsecond ) {
std::cerr << "Error, pictures must have identical dimensions!\n" ;
return 2 ;
}
for ( int y = 0 ; y < h ; y++ ) {
uint *firstLine = ( uint* )firstImage.scanLine( y ) ;
uint *secondLine = ( uint* )secondImage.scanLine( y ) ;
for ( int x = 0 ; x < w ; x++ ) {
uint pixelFirst = firstLine[ x ] ;
int rFirst = qRed( pixelFirst ) ;
int gFirst = qGreen( pixelFirst ) ;
int bFirst = qBlue( pixelFirst ) ;
uint pixelSecond = secondLine[ x ] ;
int rSecond = qRed( pixelSecond ) ;
int gSecond = qGreen( pixelSecond ) ;
int bSecond = qBlue( pixelSecond ) ;
totaldiff += std::abs( rFirst - rSecond ) / 255.0 ;
totaldiff += std::abs( gFirst - gSecond ) / 255.0 ;
totaldiff += std::abs( bFirst -bSecond ) / 255.0 ;
}
}
std::cout << "The difference of the two pictures is " <<
(totaldiff * 100) / (w * h * 3) << " % !\n" ;
return 0 ;
}
|
Rewrite this program in Java while keeping its functionality equivalent to the D version. | import std.stdio, std.exception, std.range, std.math, bitmap;
void main() {
Image!RGB i1, i2;
i1 = i1.loadPPM6("Lenna50.ppm");
i2 = i2.loadPPM6("Lenna100.ppm");
enforce(i1.nx == i2.nx && i1.ny == i2.ny, "Different sizes.");
real dif = 0.0;
foreach (p, q; zip(i1.image, i2.image))
dif += abs(p.r - q.r) + abs(p.g - q.g) + abs(p.b - q.b);
immutable nData = i1.nx * i1.ny * 3;
writeln("Difference (percentage): ",
(dif / 255.0 * 100) / nData);
}
| import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public enum ImgDiffPercent {
;
public static void main(String[] args) throws IOException {
BufferedImage img1 = ImageIO.read(new File("Lenna50.jpg"));
BufferedImage img2 = ImageIO.read(new File("Lenna100.jpg"));
double p = getDifferencePercent(img1, img2);
System.out.println("diff percent: " + p);
}
private static double getDifferencePercent(BufferedImage img1, BufferedImage img2) {
int width = img1.getWidth();
int height = img1.getHeight();
int width2 = img2.getWidth();
int height2 = img2.getHeight();
if (width != width2 || height != height2) {
throw new IllegalArgumentException(String.format("Images must have the same dimensions: (%d,%d) vs. (%d,%d)", width, height, width2, height2));
}
long diff = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
diff += pixelDiff(img1.getRGB(x, y), img2.getRGB(x, y));
}
}
long maxDiff = 3L * 255 * width * height;
return 100.0 * diff / maxDiff;
}
private static int pixelDiff(int rgb1, int rgb2) {
int r1 = (rgb1 >> 16) & 0xff;
int g1 = (rgb1 >> 8) & 0xff;
int b1 = rgb1 & 0xff;
int r2 = (rgb2 >> 16) & 0xff;
int g2 = (rgb2 >> 8) & 0xff;
int b2 = rgb2 & 0xff;
return Math.abs(r1 - r2) + Math.abs(g1 - g2) + Math.abs(b1 - b2);
}
}
|
Keep all operations the same but rewrite the snippet in Python. | import std.stdio, std.exception, std.range, std.math, bitmap;
void main() {
Image!RGB i1, i2;
i1 = i1.loadPPM6("Lenna50.ppm");
i2 = i2.loadPPM6("Lenna100.ppm");
enforce(i1.nx == i2.nx && i1.ny == i2.ny, "Different sizes.");
real dif = 0.0;
foreach (p, q; zip(i1.image, i2.image))
dif += abs(p.r - q.r) + abs(p.g - q.g) + abs(p.b - q.b);
immutable nData = i1.nx * i1.ny * 3;
writeln("Difference (percentage): ",
(dif / 255.0 * 100) / nData);
}
| from PIL import Image
i1 = Image.open("image1.jpg")
i2 = Image.open("image2.jpg")
assert i1.mode == i2.mode, "Different kinds of images."
assert i1.size == i2.size, "Different sizes."
pairs = zip(i1.getdata(), i2.getdata())
if len(i1.getbands()) == 1:
dif = sum(abs(p1-p2) for p1,p2 in pairs)
else:
dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2))
ncomponents = i1.size[0] * i1.size[1] * 3
print ("Difference (percentage):", (dif / 255.0 * 100) / ncomponents)
|
Rewrite the snippet below in Go so it works the same as the original D code. | import std.stdio, std.exception, std.range, std.math, bitmap;
void main() {
Image!RGB i1, i2;
i1 = i1.loadPPM6("Lenna50.ppm");
i2 = i2.loadPPM6("Lenna100.ppm");
enforce(i1.nx == i2.nx && i1.ny == i2.ny, "Different sizes.");
real dif = 0.0;
foreach (p, q; zip(i1.image, i2.image))
dif += abs(p.r - q.r) + abs(p.g - q.g) + abs(p.b - q.b);
immutable nData = i1.nx * i1.ny * 3;
writeln("Difference (percentage): ",
(dif / 255.0 * 100) / nData);
}
| package main
import (
"fmt"
"image/jpeg"
"os"
"log"
"image"
)
func loadJpeg(filename string) (image.Image, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
img, err := jpeg.Decode(f)
if err != nil {
return nil, err
}
return img, nil
}
func diff(a, b uint32) int64 {
if a > b {
return int64(a - b)
}
return int64(b - a)
}
func main() {
i50, err := loadJpeg("Lenna50.jpg")
if err != nil {
log.Fatal(err)
}
i100, err := loadJpeg("Lenna100.jpg")
if err != nil {
log.Fatal(err)
}
if i50.ColorModel() != i100.ColorModel() {
log.Fatal("different color models")
}
b := i50.Bounds()
if !b.Eq(i100.Bounds()) {
log.Fatal("different image sizes")
}
var sum int64
for y := b.Min.Y; y < b.Max.Y; y++ {
for x := b.Min.X; x < b.Max.X; x++ {
r1, g1, b1, _ := i50.At(x, y).RGBA()
r2, g2, b2, _ := i100.At(x, y).RGBA()
sum += diff(r1, r2)
sum += diff(g1, g2)
sum += diff(b1, b2)
}
}
nPixels := (b.Max.X - b.Min.X) * (b.Max.Y - b.Min.Y)
fmt.Printf("Image difference: %f%%\n",
float64(sum*100)/(float64(nPixels)*0xffff*3))
}
|
Rewrite this program in C while keeping its functionality equivalent to the F# version. |
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))
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define RED_C 0
#define GREEN_C 1
#define BLUE_C 2
#define GET_PIXEL(IMG, X, Y) ((IMG)->buf[ (Y) * (IMG)->width + (X) ])
int main(int argc, char **argv)
{
image im1, im2;
double totalDiff = 0.0;
unsigned int x, y;
if ( argc < 3 )
{
fprintf(stderr, "usage:\n%s FILE1 FILE2\n", argv[0]);
exit(1);
}
im1 = read_image(argv[1]);
if ( im1 == NULL ) exit(1);
im2 = read_image(argv[2]);
if ( im2 == NULL ) { free_img(im1); exit(1); }
if ( (im1->width != im2->width) || (im1->height != im2->height) )
{
fprintf(stderr, "width/height of the images must match!\n");
} else {
for(x=0; x < im1->width; x++)
{
for(y=0; y < im1->width; y++)
{
totalDiff += fabs( GET_PIXEL(im1, x, y)[RED_C] - GET_PIXEL(im2, x, y)[RED_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[GREEN_C] - GET_PIXEL(im2, x, y)[GREEN_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[BLUE_C] - GET_PIXEL(im2, x, y)[BLUE_C] ) / 255.0;
}
}
printf("%lf\n", 100.0 * totalDiff / (double)(im1->width * im1->height * 3) );
}
free_img(im1);
free_img(im2);
}
|
Rewrite this program in C# while keeping its functionality equivalent to the F# version. |
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))
| using System;
using System.Drawing;
class Program
{
static void Main()
{
Bitmap img1 = new Bitmap("Lenna50.jpg");
Bitmap img2 = new Bitmap("Lenna100.jpg");
if (img1.Size != img2.Size)
{
Console.Error.WriteLine("Images are of different sizes");
return;
}
float diff = 0;
for (int y = 0; y < img1.Height; y++)
{
for (int x = 0; x < img1.Width; x++)
{
Color pixel1 = img1.GetPixel(x, y);
Color pixel2 = img2.GetPixel(x, y);
diff += Math.Abs(pixel1.R - pixel2.R);
diff += Math.Abs(pixel1.G - pixel2.G);
diff += Math.Abs(pixel1.B - pixel2.B);
}
}
Console.WriteLine("diff: {0} %", 100 * (diff / 255) / (img1.Width * img1.Height * 3));
}
}
|
Maintain the same structure and functionality when rewriting this code in C++. |
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))
| #include <QImage>
#include <cstdlib>
#include <QColor>
#include <iostream>
int main( int argc , char *argv[ ] ) {
if ( argc != 3 ) {
std::cout << "Call this with imagecompare <file of image 1>"
<< " <file of image 2>\n" ;
return 1 ;
}
QImage firstImage ( argv[ 1 ] ) ;
QImage secondImage ( argv[ 2 ] ) ;
double totaldiff = 0.0 ;
int h = firstImage.height( ) ;
int w = firstImage.width( ) ;
int hsecond = secondImage.height( ) ;
int wsecond = secondImage.width( ) ;
if ( w != wsecond || h != hsecond ) {
std::cerr << "Error, pictures must have identical dimensions!\n" ;
return 2 ;
}
for ( int y = 0 ; y < h ; y++ ) {
uint *firstLine = ( uint* )firstImage.scanLine( y ) ;
uint *secondLine = ( uint* )secondImage.scanLine( y ) ;
for ( int x = 0 ; x < w ; x++ ) {
uint pixelFirst = firstLine[ x ] ;
int rFirst = qRed( pixelFirst ) ;
int gFirst = qGreen( pixelFirst ) ;
int bFirst = qBlue( pixelFirst ) ;
uint pixelSecond = secondLine[ x ] ;
int rSecond = qRed( pixelSecond ) ;
int gSecond = qGreen( pixelSecond ) ;
int bSecond = qBlue( pixelSecond ) ;
totaldiff += std::abs( rFirst - rSecond ) / 255.0 ;
totaldiff += std::abs( gFirst - gSecond ) / 255.0 ;
totaldiff += std::abs( bFirst -bSecond ) / 255.0 ;
}
}
std::cout << "The difference of the two pictures is " <<
(totaldiff * 100) / (w * h * 3) << " % !\n" ;
return 0 ;
}
|
Write a version of this F# function in Java with identical behavior. |
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))
| import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public enum ImgDiffPercent {
;
public static void main(String[] args) throws IOException {
BufferedImage img1 = ImageIO.read(new File("Lenna50.jpg"));
BufferedImage img2 = ImageIO.read(new File("Lenna100.jpg"));
double p = getDifferencePercent(img1, img2);
System.out.println("diff percent: " + p);
}
private static double getDifferencePercent(BufferedImage img1, BufferedImage img2) {
int width = img1.getWidth();
int height = img1.getHeight();
int width2 = img2.getWidth();
int height2 = img2.getHeight();
if (width != width2 || height != height2) {
throw new IllegalArgumentException(String.format("Images must have the same dimensions: (%d,%d) vs. (%d,%d)", width, height, width2, height2));
}
long diff = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
diff += pixelDiff(img1.getRGB(x, y), img2.getRGB(x, y));
}
}
long maxDiff = 3L * 255 * width * height;
return 100.0 * diff / maxDiff;
}
private static int pixelDiff(int rgb1, int rgb2) {
int r1 = (rgb1 >> 16) & 0xff;
int g1 = (rgb1 >> 8) & 0xff;
int b1 = rgb1 & 0xff;
int r2 = (rgb2 >> 16) & 0xff;
int g2 = (rgb2 >> 8) & 0xff;
int b2 = rgb2 & 0xff;
return Math.abs(r1 - r2) + Math.abs(g1 - g2) + Math.abs(b1 - b2);
}
}
|
Produce a language-to-language conversion: from F# to Python, same semantics. |
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))
| from PIL import Image
i1 = Image.open("image1.jpg")
i2 = Image.open("image2.jpg")
assert i1.mode == i2.mode, "Different kinds of images."
assert i1.size == i2.size, "Different sizes."
pairs = zip(i1.getdata(), i2.getdata())
if len(i1.getbands()) == 1:
dif = sum(abs(p1-p2) for p1,p2 in pairs)
else:
dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2))
ncomponents = i1.size[0] * i1.size[1] * 3
print ("Difference (percentage):", (dif / 255.0 * 100) / ncomponents)
|
Write the same code in Go as shown below in F#. |
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))
| package main
import (
"fmt"
"image/jpeg"
"os"
"log"
"image"
)
func loadJpeg(filename string) (image.Image, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
img, err := jpeg.Decode(f)
if err != nil {
return nil, err
}
return img, nil
}
func diff(a, b uint32) int64 {
if a > b {
return int64(a - b)
}
return int64(b - a)
}
func main() {
i50, err := loadJpeg("Lenna50.jpg")
if err != nil {
log.Fatal(err)
}
i100, err := loadJpeg("Lenna100.jpg")
if err != nil {
log.Fatal(err)
}
if i50.ColorModel() != i100.ColorModel() {
log.Fatal("different color models")
}
b := i50.Bounds()
if !b.Eq(i100.Bounds()) {
log.Fatal("different image sizes")
}
var sum int64
for y := b.Min.Y; y < b.Max.Y; y++ {
for x := b.Min.X; x < b.Max.X; x++ {
r1, g1, b1, _ := i50.At(x, y).RGBA()
r2, g2, b2, _ := i100.At(x, y).RGBA()
sum += diff(r1, r2)
sum += diff(g1, g2)
sum += diff(b1, b2)
}
}
nPixels := (b.Max.X - b.Min.X) * (b.Max.Y - b.Min.Y)
fmt.Printf("Image difference: %f%%\n",
float64(sum*100)/(float64(nPixels)*0xffff*3))
}
|
Generate an equivalent C version of this Forth code. | : pixel-diff
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
- abs r> + r> + ;
: bdiff
2dup bdim rot bdim d<> abort" images not comparable"
0e
dup bdim * >r
bdata swap bdata
r@ 0 do
over @ over @ pixel-diff 0 d>f f+
cell+ swap cell+
loop 2drop
r> 3 * 255 * 0 d>f f/ ;
: .bdiff
cr bdiff 100e f* f. ." percent different" ;
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define RED_C 0
#define GREEN_C 1
#define BLUE_C 2
#define GET_PIXEL(IMG, X, Y) ((IMG)->buf[ (Y) * (IMG)->width + (X) ])
int main(int argc, char **argv)
{
image im1, im2;
double totalDiff = 0.0;
unsigned int x, y;
if ( argc < 3 )
{
fprintf(stderr, "usage:\n%s FILE1 FILE2\n", argv[0]);
exit(1);
}
im1 = read_image(argv[1]);
if ( im1 == NULL ) exit(1);
im2 = read_image(argv[2]);
if ( im2 == NULL ) { free_img(im1); exit(1); }
if ( (im1->width != im2->width) || (im1->height != im2->height) )
{
fprintf(stderr, "width/height of the images must match!\n");
} else {
for(x=0; x < im1->width; x++)
{
for(y=0; y < im1->width; y++)
{
totalDiff += fabs( GET_PIXEL(im1, x, y)[RED_C] - GET_PIXEL(im2, x, y)[RED_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[GREEN_C] - GET_PIXEL(im2, x, y)[GREEN_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[BLUE_C] - GET_PIXEL(im2, x, y)[BLUE_C] ) / 255.0;
}
}
printf("%lf\n", 100.0 * totalDiff / (double)(im1->width * im1->height * 3) );
}
free_img(im1);
free_img(im2);
}
|
Write the same algorithm in C# as shown in this Forth implementation. | : pixel-diff
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
- abs r> + r> + ;
: bdiff
2dup bdim rot bdim d<> abort" images not comparable"
0e
dup bdim * >r
bdata swap bdata
r@ 0 do
over @ over @ pixel-diff 0 d>f f+
cell+ swap cell+
loop 2drop
r> 3 * 255 * 0 d>f f/ ;
: .bdiff
cr bdiff 100e f* f. ." percent different" ;
| using System;
using System.Drawing;
class Program
{
static void Main()
{
Bitmap img1 = new Bitmap("Lenna50.jpg");
Bitmap img2 = new Bitmap("Lenna100.jpg");
if (img1.Size != img2.Size)
{
Console.Error.WriteLine("Images are of different sizes");
return;
}
float diff = 0;
for (int y = 0; y < img1.Height; y++)
{
for (int x = 0; x < img1.Width; x++)
{
Color pixel1 = img1.GetPixel(x, y);
Color pixel2 = img2.GetPixel(x, y);
diff += Math.Abs(pixel1.R - pixel2.R);
diff += Math.Abs(pixel1.G - pixel2.G);
diff += Math.Abs(pixel1.B - pixel2.B);
}
}
Console.WriteLine("diff: {0} %", 100 * (diff / 255) / (img1.Width * img1.Height * 3));
}
}
|
Can you help me rewrite this code in C++ instead of Forth, keeping it the same logically? | : pixel-diff
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
- abs r> + r> + ;
: bdiff
2dup bdim rot bdim d<> abort" images not comparable"
0e
dup bdim * >r
bdata swap bdata
r@ 0 do
over @ over @ pixel-diff 0 d>f f+
cell+ swap cell+
loop 2drop
r> 3 * 255 * 0 d>f f/ ;
: .bdiff
cr bdiff 100e f* f. ." percent different" ;
| #include <QImage>
#include <cstdlib>
#include <QColor>
#include <iostream>
int main( int argc , char *argv[ ] ) {
if ( argc != 3 ) {
std::cout << "Call this with imagecompare <file of image 1>"
<< " <file of image 2>\n" ;
return 1 ;
}
QImage firstImage ( argv[ 1 ] ) ;
QImage secondImage ( argv[ 2 ] ) ;
double totaldiff = 0.0 ;
int h = firstImage.height( ) ;
int w = firstImage.width( ) ;
int hsecond = secondImage.height( ) ;
int wsecond = secondImage.width( ) ;
if ( w != wsecond || h != hsecond ) {
std::cerr << "Error, pictures must have identical dimensions!\n" ;
return 2 ;
}
for ( int y = 0 ; y < h ; y++ ) {
uint *firstLine = ( uint* )firstImage.scanLine( y ) ;
uint *secondLine = ( uint* )secondImage.scanLine( y ) ;
for ( int x = 0 ; x < w ; x++ ) {
uint pixelFirst = firstLine[ x ] ;
int rFirst = qRed( pixelFirst ) ;
int gFirst = qGreen( pixelFirst ) ;
int bFirst = qBlue( pixelFirst ) ;
uint pixelSecond = secondLine[ x ] ;
int rSecond = qRed( pixelSecond ) ;
int gSecond = qGreen( pixelSecond ) ;
int bSecond = qBlue( pixelSecond ) ;
totaldiff += std::abs( rFirst - rSecond ) / 255.0 ;
totaldiff += std::abs( gFirst - gSecond ) / 255.0 ;
totaldiff += std::abs( bFirst -bSecond ) / 255.0 ;
}
}
std::cout << "The difference of the two pictures is " <<
(totaldiff * 100) / (w * h * 3) << " % !\n" ;
return 0 ;
}
|
Convert this Forth block to Java, preserving its control flow and logic. | : pixel-diff
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
- abs r> + r> + ;
: bdiff
2dup bdim rot bdim d<> abort" images not comparable"
0e
dup bdim * >r
bdata swap bdata
r@ 0 do
over @ over @ pixel-diff 0 d>f f+
cell+ swap cell+
loop 2drop
r> 3 * 255 * 0 d>f f/ ;
: .bdiff
cr bdiff 100e f* f. ." percent different" ;
| import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public enum ImgDiffPercent {
;
public static void main(String[] args) throws IOException {
BufferedImage img1 = ImageIO.read(new File("Lenna50.jpg"));
BufferedImage img2 = ImageIO.read(new File("Lenna100.jpg"));
double p = getDifferencePercent(img1, img2);
System.out.println("diff percent: " + p);
}
private static double getDifferencePercent(BufferedImage img1, BufferedImage img2) {
int width = img1.getWidth();
int height = img1.getHeight();
int width2 = img2.getWidth();
int height2 = img2.getHeight();
if (width != width2 || height != height2) {
throw new IllegalArgumentException(String.format("Images must have the same dimensions: (%d,%d) vs. (%d,%d)", width, height, width2, height2));
}
long diff = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
diff += pixelDiff(img1.getRGB(x, y), img2.getRGB(x, y));
}
}
long maxDiff = 3L * 255 * width * height;
return 100.0 * diff / maxDiff;
}
private static int pixelDiff(int rgb1, int rgb2) {
int r1 = (rgb1 >> 16) & 0xff;
int g1 = (rgb1 >> 8) & 0xff;
int b1 = rgb1 & 0xff;
int r2 = (rgb2 >> 16) & 0xff;
int g2 = (rgb2 >> 8) & 0xff;
int b2 = rgb2 & 0xff;
return Math.abs(r1 - r2) + Math.abs(g1 - g2) + Math.abs(b1 - b2);
}
}
|
Maintain the same structure and functionality when rewriting this code in Python. | : pixel-diff
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
- abs r> + r> + ;
: bdiff
2dup bdim rot bdim d<> abort" images not comparable"
0e
dup bdim * >r
bdata swap bdata
r@ 0 do
over @ over @ pixel-diff 0 d>f f+
cell+ swap cell+
loop 2drop
r> 3 * 255 * 0 d>f f/ ;
: .bdiff
cr bdiff 100e f* f. ." percent different" ;
| from PIL import Image
i1 = Image.open("image1.jpg")
i2 = Image.open("image2.jpg")
assert i1.mode == i2.mode, "Different kinds of images."
assert i1.size == i2.size, "Different sizes."
pairs = zip(i1.getdata(), i2.getdata())
if len(i1.getbands()) == 1:
dif = sum(abs(p1-p2) for p1,p2 in pairs)
else:
dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2))
ncomponents = i1.size[0] * i1.size[1] * 3
print ("Difference (percentage):", (dif / 255.0 * 100) / ncomponents)
|
Port the following code from Forth to Go with equivalent syntax and logic. | : pixel-diff
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
- abs r> + r> + ;
: bdiff
2dup bdim rot bdim d<> abort" images not comparable"
0e
dup bdim * >r
bdata swap bdata
r@ 0 do
over @ over @ pixel-diff 0 d>f f+
cell+ swap cell+
loop 2drop
r> 3 * 255 * 0 d>f f/ ;
: .bdiff
cr bdiff 100e f* f. ." percent different" ;
| package main
import (
"fmt"
"image/jpeg"
"os"
"log"
"image"
)
func loadJpeg(filename string) (image.Image, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
img, err := jpeg.Decode(f)
if err != nil {
return nil, err
}
return img, nil
}
func diff(a, b uint32) int64 {
if a > b {
return int64(a - b)
}
return int64(b - a)
}
func main() {
i50, err := loadJpeg("Lenna50.jpg")
if err != nil {
log.Fatal(err)
}
i100, err := loadJpeg("Lenna100.jpg")
if err != nil {
log.Fatal(err)
}
if i50.ColorModel() != i100.ColorModel() {
log.Fatal("different color models")
}
b := i50.Bounds()
if !b.Eq(i100.Bounds()) {
log.Fatal("different image sizes")
}
var sum int64
for y := b.Min.Y; y < b.Max.Y; y++ {
for x := b.Min.X; x < b.Max.X; x++ {
r1, g1, b1, _ := i50.At(x, y).RGBA()
r2, g2, b2, _ := i100.At(x, y).RGBA()
sum += diff(r1, r2)
sum += diff(g1, g2)
sum += diff(b1, b2)
}
}
nPixels := (b.Max.X - b.Min.X) * (b.Max.Y - b.Min.Y)
fmt.Printf("Image difference: %f%%\n",
float64(sum*100)/(float64(nPixels)*0xffff*3))
}
|
Produce a functionally identical C# code for the snippet given in Fortran. | program ImageDifference
use RCImageBasic
use RCImageIO
implicit none
integer, parameter :: input1_u = 20, &
input2_u = 21
type(rgbimage) :: lenna1, lenna2
real :: totaldiff
open(input1_u, file="Lenna100.ppm", action="read")
open(input2_u, file="Lenna50.ppm", action="read")
call read_ppm(input1_u, lenna1)
call read_ppm(input2_u, lenna2)
close(input1_u)
close(input2_u)
totaldiff = sum( (abs(lenna1%red - lenna2%red) + &
abs(lenna1%green - lenna2%green) + &
abs(lenna1%blue - lenna2%blue)) / 255.0 )
print *, 100.0 * totaldiff / (lenna1%width * lenna1%height * 3.0)
call free_img(lenna1)
call free_img(lenna2)
end program ImageDifference
| using System;
using System.Drawing;
class Program
{
static void Main()
{
Bitmap img1 = new Bitmap("Lenna50.jpg");
Bitmap img2 = new Bitmap("Lenna100.jpg");
if (img1.Size != img2.Size)
{
Console.Error.WriteLine("Images are of different sizes");
return;
}
float diff = 0;
for (int y = 0; y < img1.Height; y++)
{
for (int x = 0; x < img1.Width; x++)
{
Color pixel1 = img1.GetPixel(x, y);
Color pixel2 = img2.GetPixel(x, y);
diff += Math.Abs(pixel1.R - pixel2.R);
diff += Math.Abs(pixel1.G - pixel2.G);
diff += Math.Abs(pixel1.B - pixel2.B);
}
}
Console.WriteLine("diff: {0} %", 100 * (diff / 255) / (img1.Width * img1.Height * 3));
}
}
|
Write a version of this Fortran function in C++ with identical behavior. | program ImageDifference
use RCImageBasic
use RCImageIO
implicit none
integer, parameter :: input1_u = 20, &
input2_u = 21
type(rgbimage) :: lenna1, lenna2
real :: totaldiff
open(input1_u, file="Lenna100.ppm", action="read")
open(input2_u, file="Lenna50.ppm", action="read")
call read_ppm(input1_u, lenna1)
call read_ppm(input2_u, lenna2)
close(input1_u)
close(input2_u)
totaldiff = sum( (abs(lenna1%red - lenna2%red) + &
abs(lenna1%green - lenna2%green) + &
abs(lenna1%blue - lenna2%blue)) / 255.0 )
print *, 100.0 * totaldiff / (lenna1%width * lenna1%height * 3.0)
call free_img(lenna1)
call free_img(lenna2)
end program ImageDifference
| #include <QImage>
#include <cstdlib>
#include <QColor>
#include <iostream>
int main( int argc , char *argv[ ] ) {
if ( argc != 3 ) {
std::cout << "Call this with imagecompare <file of image 1>"
<< " <file of image 2>\n" ;
return 1 ;
}
QImage firstImage ( argv[ 1 ] ) ;
QImage secondImage ( argv[ 2 ] ) ;
double totaldiff = 0.0 ;
int h = firstImage.height( ) ;
int w = firstImage.width( ) ;
int hsecond = secondImage.height( ) ;
int wsecond = secondImage.width( ) ;
if ( w != wsecond || h != hsecond ) {
std::cerr << "Error, pictures must have identical dimensions!\n" ;
return 2 ;
}
for ( int y = 0 ; y < h ; y++ ) {
uint *firstLine = ( uint* )firstImage.scanLine( y ) ;
uint *secondLine = ( uint* )secondImage.scanLine( y ) ;
for ( int x = 0 ; x < w ; x++ ) {
uint pixelFirst = firstLine[ x ] ;
int rFirst = qRed( pixelFirst ) ;
int gFirst = qGreen( pixelFirst ) ;
int bFirst = qBlue( pixelFirst ) ;
uint pixelSecond = secondLine[ x ] ;
int rSecond = qRed( pixelSecond ) ;
int gSecond = qGreen( pixelSecond ) ;
int bSecond = qBlue( pixelSecond ) ;
totaldiff += std::abs( rFirst - rSecond ) / 255.0 ;
totaldiff += std::abs( gFirst - gSecond ) / 255.0 ;
totaldiff += std::abs( bFirst -bSecond ) / 255.0 ;
}
}
std::cout << "The difference of the two pictures is " <<
(totaldiff * 100) / (w * h * 3) << " % !\n" ;
return 0 ;
}
|
Write the same algorithm in C as shown in this Fortran implementation. | program ImageDifference
use RCImageBasic
use RCImageIO
implicit none
integer, parameter :: input1_u = 20, &
input2_u = 21
type(rgbimage) :: lenna1, lenna2
real :: totaldiff
open(input1_u, file="Lenna100.ppm", action="read")
open(input2_u, file="Lenna50.ppm", action="read")
call read_ppm(input1_u, lenna1)
call read_ppm(input2_u, lenna2)
close(input1_u)
close(input2_u)
totaldiff = sum( (abs(lenna1%red - lenna2%red) + &
abs(lenna1%green - lenna2%green) + &
abs(lenna1%blue - lenna2%blue)) / 255.0 )
print *, 100.0 * totaldiff / (lenna1%width * lenna1%height * 3.0)
call free_img(lenna1)
call free_img(lenna2)
end program ImageDifference
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define RED_C 0
#define GREEN_C 1
#define BLUE_C 2
#define GET_PIXEL(IMG, X, Y) ((IMG)->buf[ (Y) * (IMG)->width + (X) ])
int main(int argc, char **argv)
{
image im1, im2;
double totalDiff = 0.0;
unsigned int x, y;
if ( argc < 3 )
{
fprintf(stderr, "usage:\n%s FILE1 FILE2\n", argv[0]);
exit(1);
}
im1 = read_image(argv[1]);
if ( im1 == NULL ) exit(1);
im2 = read_image(argv[2]);
if ( im2 == NULL ) { free_img(im1); exit(1); }
if ( (im1->width != im2->width) || (im1->height != im2->height) )
{
fprintf(stderr, "width/height of the images must match!\n");
} else {
for(x=0; x < im1->width; x++)
{
for(y=0; y < im1->width; y++)
{
totalDiff += fabs( GET_PIXEL(im1, x, y)[RED_C] - GET_PIXEL(im2, x, y)[RED_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[GREEN_C] - GET_PIXEL(im2, x, y)[GREEN_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[BLUE_C] - GET_PIXEL(im2, x, y)[BLUE_C] ) / 255.0;
}
}
printf("%lf\n", 100.0 * totalDiff / (double)(im1->width * im1->height * 3) );
}
free_img(im1);
free_img(im2);
}
|
Can you help me rewrite this code in Go instead of Fortran, keeping it the same logically? | program ImageDifference
use RCImageBasic
use RCImageIO
implicit none
integer, parameter :: input1_u = 20, &
input2_u = 21
type(rgbimage) :: lenna1, lenna2
real :: totaldiff
open(input1_u, file="Lenna100.ppm", action="read")
open(input2_u, file="Lenna50.ppm", action="read")
call read_ppm(input1_u, lenna1)
call read_ppm(input2_u, lenna2)
close(input1_u)
close(input2_u)
totaldiff = sum( (abs(lenna1%red - lenna2%red) + &
abs(lenna1%green - lenna2%green) + &
abs(lenna1%blue - lenna2%blue)) / 255.0 )
print *, 100.0 * totaldiff / (lenna1%width * lenna1%height * 3.0)
call free_img(lenna1)
call free_img(lenna2)
end program ImageDifference
| package main
import (
"fmt"
"image/jpeg"
"os"
"log"
"image"
)
func loadJpeg(filename string) (image.Image, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
img, err := jpeg.Decode(f)
if err != nil {
return nil, err
}
return img, nil
}
func diff(a, b uint32) int64 {
if a > b {
return int64(a - b)
}
return int64(b - a)
}
func main() {
i50, err := loadJpeg("Lenna50.jpg")
if err != nil {
log.Fatal(err)
}
i100, err := loadJpeg("Lenna100.jpg")
if err != nil {
log.Fatal(err)
}
if i50.ColorModel() != i100.ColorModel() {
log.Fatal("different color models")
}
b := i50.Bounds()
if !b.Eq(i100.Bounds()) {
log.Fatal("different image sizes")
}
var sum int64
for y := b.Min.Y; y < b.Max.Y; y++ {
for x := b.Min.X; x < b.Max.X; x++ {
r1, g1, b1, _ := i50.At(x, y).RGBA()
r2, g2, b2, _ := i100.At(x, y).RGBA()
sum += diff(r1, r2)
sum += diff(g1, g2)
sum += diff(b1, b2)
}
}
nPixels := (b.Max.X - b.Min.X) * (b.Max.Y - b.Min.Y)
fmt.Printf("Image difference: %f%%\n",
float64(sum*100)/(float64(nPixels)*0xffff*3))
}
|
Generate a Java translation of this Fortran snippet without changing its computational steps. | program ImageDifference
use RCImageBasic
use RCImageIO
implicit none
integer, parameter :: input1_u = 20, &
input2_u = 21
type(rgbimage) :: lenna1, lenna2
real :: totaldiff
open(input1_u, file="Lenna100.ppm", action="read")
open(input2_u, file="Lenna50.ppm", action="read")
call read_ppm(input1_u, lenna1)
call read_ppm(input2_u, lenna2)
close(input1_u)
close(input2_u)
totaldiff = sum( (abs(lenna1%red - lenna2%red) + &
abs(lenna1%green - lenna2%green) + &
abs(lenna1%blue - lenna2%blue)) / 255.0 )
print *, 100.0 * totaldiff / (lenna1%width * lenna1%height * 3.0)
call free_img(lenna1)
call free_img(lenna2)
end program ImageDifference
| import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public enum ImgDiffPercent {
;
public static void main(String[] args) throws IOException {
BufferedImage img1 = ImageIO.read(new File("Lenna50.jpg"));
BufferedImage img2 = ImageIO.read(new File("Lenna100.jpg"));
double p = getDifferencePercent(img1, img2);
System.out.println("diff percent: " + p);
}
private static double getDifferencePercent(BufferedImage img1, BufferedImage img2) {
int width = img1.getWidth();
int height = img1.getHeight();
int width2 = img2.getWidth();
int height2 = img2.getHeight();
if (width != width2 || height != height2) {
throw new IllegalArgumentException(String.format("Images must have the same dimensions: (%d,%d) vs. (%d,%d)", width, height, width2, height2));
}
long diff = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
diff += pixelDiff(img1.getRGB(x, y), img2.getRGB(x, y));
}
}
long maxDiff = 3L * 255 * width * height;
return 100.0 * diff / maxDiff;
}
private static int pixelDiff(int rgb1, int rgb2) {
int r1 = (rgb1 >> 16) & 0xff;
int g1 = (rgb1 >> 8) & 0xff;
int b1 = rgb1 & 0xff;
int r2 = (rgb2 >> 16) & 0xff;
int g2 = (rgb2 >> 8) & 0xff;
int b2 = rgb2 & 0xff;
return Math.abs(r1 - r2) + Math.abs(g1 - g2) + Math.abs(b1 - b2);
}
}
|
Translate this program into Python but keep the logic exactly as in Fortran. | program ImageDifference
use RCImageBasic
use RCImageIO
implicit none
integer, parameter :: input1_u = 20, &
input2_u = 21
type(rgbimage) :: lenna1, lenna2
real :: totaldiff
open(input1_u, file="Lenna100.ppm", action="read")
open(input2_u, file="Lenna50.ppm", action="read")
call read_ppm(input1_u, lenna1)
call read_ppm(input2_u, lenna2)
close(input1_u)
close(input2_u)
totaldiff = sum( (abs(lenna1%red - lenna2%red) + &
abs(lenna1%green - lenna2%green) + &
abs(lenna1%blue - lenna2%blue)) / 255.0 )
print *, 100.0 * totaldiff / (lenna1%width * lenna1%height * 3.0)
call free_img(lenna1)
call free_img(lenna2)
end program ImageDifference
| from PIL import Image
i1 = Image.open("image1.jpg")
i2 = Image.open("image2.jpg")
assert i1.mode == i2.mode, "Different kinds of images."
assert i1.size == i2.size, "Different sizes."
pairs = zip(i1.getdata(), i2.getdata())
if len(i1.getbands()) == 1:
dif = sum(abs(p1-p2) for p1,p2 in pairs)
else:
dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2))
ncomponents = i1.size[0] * i1.size[1] * 3
print ("Difference (percentage):", (dif / 255.0 * 100) / ncomponents)
|
Transform the following Haskell implementation into C, maintaining the same output and logic. | import Bitmap
import Bitmap.Netpbm
import Bitmap.RGB
import Control.Monad
import Control.Monad.ST
import System.Environment (getArgs)
main = do
[path1, path2] <- getArgs
image1 <- readNetpbm path1
image2 <- readNetpbm path2
diff <- stToIO $ imageDiff image1 image2
putStrLn $ "Difference: " ++ show (100 * diff) ++ "%"
imageDiff :: Image s RGB -> Image s RGB -> ST s Double
imageDiff image1 image2 = do
i1 <- getPixels image1
i2 <- getPixels image2
unless (length i1 == length i2) $
fail "imageDiff: Images are of different sizes"
return $
toEnum (sum $ zipWith minus i1 i2) /
toEnum (3 * 255 * length i1)
where (RGB (r1, g1, b1)) `minus` (RGB (r2, g2, b2)) =
abs (r1 - r2) + abs (g1 - g2) + abs (b1 - b2)
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define RED_C 0
#define GREEN_C 1
#define BLUE_C 2
#define GET_PIXEL(IMG, X, Y) ((IMG)->buf[ (Y) * (IMG)->width + (X) ])
int main(int argc, char **argv)
{
image im1, im2;
double totalDiff = 0.0;
unsigned int x, y;
if ( argc < 3 )
{
fprintf(stderr, "usage:\n%s FILE1 FILE2\n", argv[0]);
exit(1);
}
im1 = read_image(argv[1]);
if ( im1 == NULL ) exit(1);
im2 = read_image(argv[2]);
if ( im2 == NULL ) { free_img(im1); exit(1); }
if ( (im1->width != im2->width) || (im1->height != im2->height) )
{
fprintf(stderr, "width/height of the images must match!\n");
} else {
for(x=0; x < im1->width; x++)
{
for(y=0; y < im1->width; y++)
{
totalDiff += fabs( GET_PIXEL(im1, x, y)[RED_C] - GET_PIXEL(im2, x, y)[RED_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[GREEN_C] - GET_PIXEL(im2, x, y)[GREEN_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[BLUE_C] - GET_PIXEL(im2, x, y)[BLUE_C] ) / 255.0;
}
}
printf("%lf\n", 100.0 * totalDiff / (double)(im1->width * im1->height * 3) );
}
free_img(im1);
free_img(im2);
}
|
Produce a functionally identical C# code for the snippet given in Haskell. | import Bitmap
import Bitmap.Netpbm
import Bitmap.RGB
import Control.Monad
import Control.Monad.ST
import System.Environment (getArgs)
main = do
[path1, path2] <- getArgs
image1 <- readNetpbm path1
image2 <- readNetpbm path2
diff <- stToIO $ imageDiff image1 image2
putStrLn $ "Difference: " ++ show (100 * diff) ++ "%"
imageDiff :: Image s RGB -> Image s RGB -> ST s Double
imageDiff image1 image2 = do
i1 <- getPixels image1
i2 <- getPixels image2
unless (length i1 == length i2) $
fail "imageDiff: Images are of different sizes"
return $
toEnum (sum $ zipWith minus i1 i2) /
toEnum (3 * 255 * length i1)
where (RGB (r1, g1, b1)) `minus` (RGB (r2, g2, b2)) =
abs (r1 - r2) + abs (g1 - g2) + abs (b1 - b2)
| using System;
using System.Drawing;
class Program
{
static void Main()
{
Bitmap img1 = new Bitmap("Lenna50.jpg");
Bitmap img2 = new Bitmap("Lenna100.jpg");
if (img1.Size != img2.Size)
{
Console.Error.WriteLine("Images are of different sizes");
return;
}
float diff = 0;
for (int y = 0; y < img1.Height; y++)
{
for (int x = 0; x < img1.Width; x++)
{
Color pixel1 = img1.GetPixel(x, y);
Color pixel2 = img2.GetPixel(x, y);
diff += Math.Abs(pixel1.R - pixel2.R);
diff += Math.Abs(pixel1.G - pixel2.G);
diff += Math.Abs(pixel1.B - pixel2.B);
}
}
Console.WriteLine("diff: {0} %", 100 * (diff / 255) / (img1.Width * img1.Height * 3));
}
}
|
Change the programming language of this snippet from Haskell to C++ without modifying what it does. | import Bitmap
import Bitmap.Netpbm
import Bitmap.RGB
import Control.Monad
import Control.Monad.ST
import System.Environment (getArgs)
main = do
[path1, path2] <- getArgs
image1 <- readNetpbm path1
image2 <- readNetpbm path2
diff <- stToIO $ imageDiff image1 image2
putStrLn $ "Difference: " ++ show (100 * diff) ++ "%"
imageDiff :: Image s RGB -> Image s RGB -> ST s Double
imageDiff image1 image2 = do
i1 <- getPixels image1
i2 <- getPixels image2
unless (length i1 == length i2) $
fail "imageDiff: Images are of different sizes"
return $
toEnum (sum $ zipWith minus i1 i2) /
toEnum (3 * 255 * length i1)
where (RGB (r1, g1, b1)) `minus` (RGB (r2, g2, b2)) =
abs (r1 - r2) + abs (g1 - g2) + abs (b1 - b2)
| #include <QImage>
#include <cstdlib>
#include <QColor>
#include <iostream>
int main( int argc , char *argv[ ] ) {
if ( argc != 3 ) {
std::cout << "Call this with imagecompare <file of image 1>"
<< " <file of image 2>\n" ;
return 1 ;
}
QImage firstImage ( argv[ 1 ] ) ;
QImage secondImage ( argv[ 2 ] ) ;
double totaldiff = 0.0 ;
int h = firstImage.height( ) ;
int w = firstImage.width( ) ;
int hsecond = secondImage.height( ) ;
int wsecond = secondImage.width( ) ;
if ( w != wsecond || h != hsecond ) {
std::cerr << "Error, pictures must have identical dimensions!\n" ;
return 2 ;
}
for ( int y = 0 ; y < h ; y++ ) {
uint *firstLine = ( uint* )firstImage.scanLine( y ) ;
uint *secondLine = ( uint* )secondImage.scanLine( y ) ;
for ( int x = 0 ; x < w ; x++ ) {
uint pixelFirst = firstLine[ x ] ;
int rFirst = qRed( pixelFirst ) ;
int gFirst = qGreen( pixelFirst ) ;
int bFirst = qBlue( pixelFirst ) ;
uint pixelSecond = secondLine[ x ] ;
int rSecond = qRed( pixelSecond ) ;
int gSecond = qGreen( pixelSecond ) ;
int bSecond = qBlue( pixelSecond ) ;
totaldiff += std::abs( rFirst - rSecond ) / 255.0 ;
totaldiff += std::abs( gFirst - gSecond ) / 255.0 ;
totaldiff += std::abs( bFirst -bSecond ) / 255.0 ;
}
}
std::cout << "The difference of the two pictures is " <<
(totaldiff * 100) / (w * h * 3) << " % !\n" ;
return 0 ;
}
|
Port the provided Haskell code into Java while preserving the original functionality. | import Bitmap
import Bitmap.Netpbm
import Bitmap.RGB
import Control.Monad
import Control.Monad.ST
import System.Environment (getArgs)
main = do
[path1, path2] <- getArgs
image1 <- readNetpbm path1
image2 <- readNetpbm path2
diff <- stToIO $ imageDiff image1 image2
putStrLn $ "Difference: " ++ show (100 * diff) ++ "%"
imageDiff :: Image s RGB -> Image s RGB -> ST s Double
imageDiff image1 image2 = do
i1 <- getPixels image1
i2 <- getPixels image2
unless (length i1 == length i2) $
fail "imageDiff: Images are of different sizes"
return $
toEnum (sum $ zipWith minus i1 i2) /
toEnum (3 * 255 * length i1)
where (RGB (r1, g1, b1)) `minus` (RGB (r2, g2, b2)) =
abs (r1 - r2) + abs (g1 - g2) + abs (b1 - b2)
| import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public enum ImgDiffPercent {
;
public static void main(String[] args) throws IOException {
BufferedImage img1 = ImageIO.read(new File("Lenna50.jpg"));
BufferedImage img2 = ImageIO.read(new File("Lenna100.jpg"));
double p = getDifferencePercent(img1, img2);
System.out.println("diff percent: " + p);
}
private static double getDifferencePercent(BufferedImage img1, BufferedImage img2) {
int width = img1.getWidth();
int height = img1.getHeight();
int width2 = img2.getWidth();
int height2 = img2.getHeight();
if (width != width2 || height != height2) {
throw new IllegalArgumentException(String.format("Images must have the same dimensions: (%d,%d) vs. (%d,%d)", width, height, width2, height2));
}
long diff = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
diff += pixelDiff(img1.getRGB(x, y), img2.getRGB(x, y));
}
}
long maxDiff = 3L * 255 * width * height;
return 100.0 * diff / maxDiff;
}
private static int pixelDiff(int rgb1, int rgb2) {
int r1 = (rgb1 >> 16) & 0xff;
int g1 = (rgb1 >> 8) & 0xff;
int b1 = rgb1 & 0xff;
int r2 = (rgb2 >> 16) & 0xff;
int g2 = (rgb2 >> 8) & 0xff;
int b2 = rgb2 & 0xff;
return Math.abs(r1 - r2) + Math.abs(g1 - g2) + Math.abs(b1 - b2);
}
}
|
Convert the following code from Haskell to Python, ensuring the logic remains intact. | import Bitmap
import Bitmap.Netpbm
import Bitmap.RGB
import Control.Monad
import Control.Monad.ST
import System.Environment (getArgs)
main = do
[path1, path2] <- getArgs
image1 <- readNetpbm path1
image2 <- readNetpbm path2
diff <- stToIO $ imageDiff image1 image2
putStrLn $ "Difference: " ++ show (100 * diff) ++ "%"
imageDiff :: Image s RGB -> Image s RGB -> ST s Double
imageDiff image1 image2 = do
i1 <- getPixels image1
i2 <- getPixels image2
unless (length i1 == length i2) $
fail "imageDiff: Images are of different sizes"
return $
toEnum (sum $ zipWith minus i1 i2) /
toEnum (3 * 255 * length i1)
where (RGB (r1, g1, b1)) `minus` (RGB (r2, g2, b2)) =
abs (r1 - r2) + abs (g1 - g2) + abs (b1 - b2)
| from PIL import Image
i1 = Image.open("image1.jpg")
i2 = Image.open("image2.jpg")
assert i1.mode == i2.mode, "Different kinds of images."
assert i1.size == i2.size, "Different sizes."
pairs = zip(i1.getdata(), i2.getdata())
if len(i1.getbands()) == 1:
dif = sum(abs(p1-p2) for p1,p2 in pairs)
else:
dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2))
ncomponents = i1.size[0] * i1.size[1] * 3
print ("Difference (percentage):", (dif / 255.0 * 100) / ncomponents)
|
Write the same code in Go as shown below in Haskell. | import Bitmap
import Bitmap.Netpbm
import Bitmap.RGB
import Control.Monad
import Control.Monad.ST
import System.Environment (getArgs)
main = do
[path1, path2] <- getArgs
image1 <- readNetpbm path1
image2 <- readNetpbm path2
diff <- stToIO $ imageDiff image1 image2
putStrLn $ "Difference: " ++ show (100 * diff) ++ "%"
imageDiff :: Image s RGB -> Image s RGB -> ST s Double
imageDiff image1 image2 = do
i1 <- getPixels image1
i2 <- getPixels image2
unless (length i1 == length i2) $
fail "imageDiff: Images are of different sizes"
return $
toEnum (sum $ zipWith minus i1 i2) /
toEnum (3 * 255 * length i1)
where (RGB (r1, g1, b1)) `minus` (RGB (r2, g2, b2)) =
abs (r1 - r2) + abs (g1 - g2) + abs (b1 - b2)
| package main
import (
"fmt"
"image/jpeg"
"os"
"log"
"image"
)
func loadJpeg(filename string) (image.Image, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
img, err := jpeg.Decode(f)
if err != nil {
return nil, err
}
return img, nil
}
func diff(a, b uint32) int64 {
if a > b {
return int64(a - b)
}
return int64(b - a)
}
func main() {
i50, err := loadJpeg("Lenna50.jpg")
if err != nil {
log.Fatal(err)
}
i100, err := loadJpeg("Lenna100.jpg")
if err != nil {
log.Fatal(err)
}
if i50.ColorModel() != i100.ColorModel() {
log.Fatal("different color models")
}
b := i50.Bounds()
if !b.Eq(i100.Bounds()) {
log.Fatal("different image sizes")
}
var sum int64
for y := b.Min.Y; y < b.Max.Y; y++ {
for x := b.Min.X; x < b.Max.X; x++ {
r1, g1, b1, _ := i50.At(x, y).RGBA()
r2, g2, b2, _ := i100.At(x, y).RGBA()
sum += diff(r1, r2)
sum += diff(g1, g2)
sum += diff(b1, b2)
}
}
nPixels := (b.Max.X - b.Min.X) * (b.Max.Y - b.Min.Y)
fmt.Printf("Image difference: %f%%\n",
float64(sum*100)/(float64(nPixels)*0xffff*3))
}
|
Change the following J code into C without altering its purpose. | require 'media/image3'
'Lenna50.jpg' (+/@,@:|@:- % 2.55 * */@$@])&read_image 'Lenna100.jpg'
1.62559
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define RED_C 0
#define GREEN_C 1
#define BLUE_C 2
#define GET_PIXEL(IMG, X, Y) ((IMG)->buf[ (Y) * (IMG)->width + (X) ])
int main(int argc, char **argv)
{
image im1, im2;
double totalDiff = 0.0;
unsigned int x, y;
if ( argc < 3 )
{
fprintf(stderr, "usage:\n%s FILE1 FILE2\n", argv[0]);
exit(1);
}
im1 = read_image(argv[1]);
if ( im1 == NULL ) exit(1);
im2 = read_image(argv[2]);
if ( im2 == NULL ) { free_img(im1); exit(1); }
if ( (im1->width != im2->width) || (im1->height != im2->height) )
{
fprintf(stderr, "width/height of the images must match!\n");
} else {
for(x=0; x < im1->width; x++)
{
for(y=0; y < im1->width; y++)
{
totalDiff += fabs( GET_PIXEL(im1, x, y)[RED_C] - GET_PIXEL(im2, x, y)[RED_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[GREEN_C] - GET_PIXEL(im2, x, y)[GREEN_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[BLUE_C] - GET_PIXEL(im2, x, y)[BLUE_C] ) / 255.0;
}
}
printf("%lf\n", 100.0 * totalDiff / (double)(im1->width * im1->height * 3) );
}
free_img(im1);
free_img(im2);
}
|
Translate this program into C# but keep the logic exactly as in J. | require 'media/image3'
'Lenna50.jpg' (+/@,@:|@:- % 2.55 * */@$@])&read_image 'Lenna100.jpg'
1.62559
| using System;
using System.Drawing;
class Program
{
static void Main()
{
Bitmap img1 = new Bitmap("Lenna50.jpg");
Bitmap img2 = new Bitmap("Lenna100.jpg");
if (img1.Size != img2.Size)
{
Console.Error.WriteLine("Images are of different sizes");
return;
}
float diff = 0;
for (int y = 0; y < img1.Height; y++)
{
for (int x = 0; x < img1.Width; x++)
{
Color pixel1 = img1.GetPixel(x, y);
Color pixel2 = img2.GetPixel(x, y);
diff += Math.Abs(pixel1.R - pixel2.R);
diff += Math.Abs(pixel1.G - pixel2.G);
diff += Math.Abs(pixel1.B - pixel2.B);
}
}
Console.WriteLine("diff: {0} %", 100 * (diff / 255) / (img1.Width * img1.Height * 3));
}
}
|
Generate a C++ translation of this J snippet without changing its computational steps. | require 'media/image3'
'Lenna50.jpg' (+/@,@:|@:- % 2.55 * */@$@])&read_image 'Lenna100.jpg'
1.62559
| #include <QImage>
#include <cstdlib>
#include <QColor>
#include <iostream>
int main( int argc , char *argv[ ] ) {
if ( argc != 3 ) {
std::cout << "Call this with imagecompare <file of image 1>"
<< " <file of image 2>\n" ;
return 1 ;
}
QImage firstImage ( argv[ 1 ] ) ;
QImage secondImage ( argv[ 2 ] ) ;
double totaldiff = 0.0 ;
int h = firstImage.height( ) ;
int w = firstImage.width( ) ;
int hsecond = secondImage.height( ) ;
int wsecond = secondImage.width( ) ;
if ( w != wsecond || h != hsecond ) {
std::cerr << "Error, pictures must have identical dimensions!\n" ;
return 2 ;
}
for ( int y = 0 ; y < h ; y++ ) {
uint *firstLine = ( uint* )firstImage.scanLine( y ) ;
uint *secondLine = ( uint* )secondImage.scanLine( y ) ;
for ( int x = 0 ; x < w ; x++ ) {
uint pixelFirst = firstLine[ x ] ;
int rFirst = qRed( pixelFirst ) ;
int gFirst = qGreen( pixelFirst ) ;
int bFirst = qBlue( pixelFirst ) ;
uint pixelSecond = secondLine[ x ] ;
int rSecond = qRed( pixelSecond ) ;
int gSecond = qGreen( pixelSecond ) ;
int bSecond = qBlue( pixelSecond ) ;
totaldiff += std::abs( rFirst - rSecond ) / 255.0 ;
totaldiff += std::abs( gFirst - gSecond ) / 255.0 ;
totaldiff += std::abs( bFirst -bSecond ) / 255.0 ;
}
}
std::cout << "The difference of the two pictures is " <<
(totaldiff * 100) / (w * h * 3) << " % !\n" ;
return 0 ;
}
|
Convert this J block to Java, preserving its control flow and logic. | require 'media/image3'
'Lenna50.jpg' (+/@,@:|@:- % 2.55 * */@$@])&read_image 'Lenna100.jpg'
1.62559
| import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public enum ImgDiffPercent {
;
public static void main(String[] args) throws IOException {
BufferedImage img1 = ImageIO.read(new File("Lenna50.jpg"));
BufferedImage img2 = ImageIO.read(new File("Lenna100.jpg"));
double p = getDifferencePercent(img1, img2);
System.out.println("diff percent: " + p);
}
private static double getDifferencePercent(BufferedImage img1, BufferedImage img2) {
int width = img1.getWidth();
int height = img1.getHeight();
int width2 = img2.getWidth();
int height2 = img2.getHeight();
if (width != width2 || height != height2) {
throw new IllegalArgumentException(String.format("Images must have the same dimensions: (%d,%d) vs. (%d,%d)", width, height, width2, height2));
}
long diff = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
diff += pixelDiff(img1.getRGB(x, y), img2.getRGB(x, y));
}
}
long maxDiff = 3L * 255 * width * height;
return 100.0 * diff / maxDiff;
}
private static int pixelDiff(int rgb1, int rgb2) {
int r1 = (rgb1 >> 16) & 0xff;
int g1 = (rgb1 >> 8) & 0xff;
int b1 = rgb1 & 0xff;
int r2 = (rgb2 >> 16) & 0xff;
int g2 = (rgb2 >> 8) & 0xff;
int b2 = rgb2 & 0xff;
return Math.abs(r1 - r2) + Math.abs(g1 - g2) + Math.abs(b1 - b2);
}
}
|
Change the following J code into Python without altering its purpose. | require 'media/image3'
'Lenna50.jpg' (+/@,@:|@:- % 2.55 * */@$@])&read_image 'Lenna100.jpg'
1.62559
| from PIL import Image
i1 = Image.open("image1.jpg")
i2 = Image.open("image2.jpg")
assert i1.mode == i2.mode, "Different kinds of images."
assert i1.size == i2.size, "Different sizes."
pairs = zip(i1.getdata(), i2.getdata())
if len(i1.getbands()) == 1:
dif = sum(abs(p1-p2) for p1,p2 in pairs)
else:
dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2))
ncomponents = i1.size[0] * i1.size[1] * 3
print ("Difference (percentage):", (dif / 255.0 * 100) / ncomponents)
|
Transform the following J implementation into Go, maintaining the same output and logic. | require 'media/image3'
'Lenna50.jpg' (+/@,@:|@:- % 2.55 * */@$@])&read_image 'Lenna100.jpg'
1.62559
| package main
import (
"fmt"
"image/jpeg"
"os"
"log"
"image"
)
func loadJpeg(filename string) (image.Image, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
img, err := jpeg.Decode(f)
if err != nil {
return nil, err
}
return img, nil
}
func diff(a, b uint32) int64 {
if a > b {
return int64(a - b)
}
return int64(b - a)
}
func main() {
i50, err := loadJpeg("Lenna50.jpg")
if err != nil {
log.Fatal(err)
}
i100, err := loadJpeg("Lenna100.jpg")
if err != nil {
log.Fatal(err)
}
if i50.ColorModel() != i100.ColorModel() {
log.Fatal("different color models")
}
b := i50.Bounds()
if !b.Eq(i100.Bounds()) {
log.Fatal("different image sizes")
}
var sum int64
for y := b.Min.Y; y < b.Max.Y; y++ {
for x := b.Min.X; x < b.Max.X; x++ {
r1, g1, b1, _ := i50.At(x, y).RGBA()
r2, g2, b2, _ := i100.At(x, y).RGBA()
sum += diff(r1, r2)
sum += diff(g1, g2)
sum += diff(b1, b2)
}
}
nPixels := (b.Max.X - b.Min.X) * (b.Max.Y - b.Min.Y)
fmt.Printf("Image difference: %f%%\n",
float64(sum*100)/(float64(nPixels)*0xffff*3))
}
|
Rewrite this program in C while keeping its functionality equivalent to the Julia version. | using Images, FileIO, Printf
absdiff(a::RGB{T}, b::RGB{T}) where T = sum(abs(col(a) - col(b)) for col in (red, green, blue))
function pctdiff(A::Matrix{Color{T}}, B::Matrix{Color{T}}) where T
size(A) != size(B) && throw(ArgumentError("images must be same-size"))
s = zero(T)
for (a, b) in zip(A, B)
s += absdiff(a, b)
end
return 100s / 3prod(size(A))
end
img50 = load("data/lenna50.jpg") |> Matrix{RGB{Float64}};
img100 = load("data/lenna100.jpg") |> Matrix{RGB{Float64}};
d = pctdiff(img50, img100)
@printf("Percentage difference: %.4f%%\n", d)
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define RED_C 0
#define GREEN_C 1
#define BLUE_C 2
#define GET_PIXEL(IMG, X, Y) ((IMG)->buf[ (Y) * (IMG)->width + (X) ])
int main(int argc, char **argv)
{
image im1, im2;
double totalDiff = 0.0;
unsigned int x, y;
if ( argc < 3 )
{
fprintf(stderr, "usage:\n%s FILE1 FILE2\n", argv[0]);
exit(1);
}
im1 = read_image(argv[1]);
if ( im1 == NULL ) exit(1);
im2 = read_image(argv[2]);
if ( im2 == NULL ) { free_img(im1); exit(1); }
if ( (im1->width != im2->width) || (im1->height != im2->height) )
{
fprintf(stderr, "width/height of the images must match!\n");
} else {
for(x=0; x < im1->width; x++)
{
for(y=0; y < im1->width; y++)
{
totalDiff += fabs( GET_PIXEL(im1, x, y)[RED_C] - GET_PIXEL(im2, x, y)[RED_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[GREEN_C] - GET_PIXEL(im2, x, y)[GREEN_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[BLUE_C] - GET_PIXEL(im2, x, y)[BLUE_C] ) / 255.0;
}
}
printf("%lf\n", 100.0 * totalDiff / (double)(im1->width * im1->height * 3) );
}
free_img(im1);
free_img(im2);
}
|
Write the same algorithm in C# as shown in this Julia implementation. | using Images, FileIO, Printf
absdiff(a::RGB{T}, b::RGB{T}) where T = sum(abs(col(a) - col(b)) for col in (red, green, blue))
function pctdiff(A::Matrix{Color{T}}, B::Matrix{Color{T}}) where T
size(A) != size(B) && throw(ArgumentError("images must be same-size"))
s = zero(T)
for (a, b) in zip(A, B)
s += absdiff(a, b)
end
return 100s / 3prod(size(A))
end
img50 = load("data/lenna50.jpg") |> Matrix{RGB{Float64}};
img100 = load("data/lenna100.jpg") |> Matrix{RGB{Float64}};
d = pctdiff(img50, img100)
@printf("Percentage difference: %.4f%%\n", d)
| using System;
using System.Drawing;
class Program
{
static void Main()
{
Bitmap img1 = new Bitmap("Lenna50.jpg");
Bitmap img2 = new Bitmap("Lenna100.jpg");
if (img1.Size != img2.Size)
{
Console.Error.WriteLine("Images are of different sizes");
return;
}
float diff = 0;
for (int y = 0; y < img1.Height; y++)
{
for (int x = 0; x < img1.Width; x++)
{
Color pixel1 = img1.GetPixel(x, y);
Color pixel2 = img2.GetPixel(x, y);
diff += Math.Abs(pixel1.R - pixel2.R);
diff += Math.Abs(pixel1.G - pixel2.G);
diff += Math.Abs(pixel1.B - pixel2.B);
}
}
Console.WriteLine("diff: {0} %", 100 * (diff / 255) / (img1.Width * img1.Height * 3));
}
}
|
Port the provided Julia code into C++ while preserving the original functionality. | using Images, FileIO, Printf
absdiff(a::RGB{T}, b::RGB{T}) where T = sum(abs(col(a) - col(b)) for col in (red, green, blue))
function pctdiff(A::Matrix{Color{T}}, B::Matrix{Color{T}}) where T
size(A) != size(B) && throw(ArgumentError("images must be same-size"))
s = zero(T)
for (a, b) in zip(A, B)
s += absdiff(a, b)
end
return 100s / 3prod(size(A))
end
img50 = load("data/lenna50.jpg") |> Matrix{RGB{Float64}};
img100 = load("data/lenna100.jpg") |> Matrix{RGB{Float64}};
d = pctdiff(img50, img100)
@printf("Percentage difference: %.4f%%\n", d)
| #include <QImage>
#include <cstdlib>
#include <QColor>
#include <iostream>
int main( int argc , char *argv[ ] ) {
if ( argc != 3 ) {
std::cout << "Call this with imagecompare <file of image 1>"
<< " <file of image 2>\n" ;
return 1 ;
}
QImage firstImage ( argv[ 1 ] ) ;
QImage secondImage ( argv[ 2 ] ) ;
double totaldiff = 0.0 ;
int h = firstImage.height( ) ;
int w = firstImage.width( ) ;
int hsecond = secondImage.height( ) ;
int wsecond = secondImage.width( ) ;
if ( w != wsecond || h != hsecond ) {
std::cerr << "Error, pictures must have identical dimensions!\n" ;
return 2 ;
}
for ( int y = 0 ; y < h ; y++ ) {
uint *firstLine = ( uint* )firstImage.scanLine( y ) ;
uint *secondLine = ( uint* )secondImage.scanLine( y ) ;
for ( int x = 0 ; x < w ; x++ ) {
uint pixelFirst = firstLine[ x ] ;
int rFirst = qRed( pixelFirst ) ;
int gFirst = qGreen( pixelFirst ) ;
int bFirst = qBlue( pixelFirst ) ;
uint pixelSecond = secondLine[ x ] ;
int rSecond = qRed( pixelSecond ) ;
int gSecond = qGreen( pixelSecond ) ;
int bSecond = qBlue( pixelSecond ) ;
totaldiff += std::abs( rFirst - rSecond ) / 255.0 ;
totaldiff += std::abs( gFirst - gSecond ) / 255.0 ;
totaldiff += std::abs( bFirst -bSecond ) / 255.0 ;
}
}
std::cout << "The difference of the two pictures is " <<
(totaldiff * 100) / (w * h * 3) << " % !\n" ;
return 0 ;
}
|
Maintain the same structure and functionality when rewriting this code in Java. | using Images, FileIO, Printf
absdiff(a::RGB{T}, b::RGB{T}) where T = sum(abs(col(a) - col(b)) for col in (red, green, blue))
function pctdiff(A::Matrix{Color{T}}, B::Matrix{Color{T}}) where T
size(A) != size(B) && throw(ArgumentError("images must be same-size"))
s = zero(T)
for (a, b) in zip(A, B)
s += absdiff(a, b)
end
return 100s / 3prod(size(A))
end
img50 = load("data/lenna50.jpg") |> Matrix{RGB{Float64}};
img100 = load("data/lenna100.jpg") |> Matrix{RGB{Float64}};
d = pctdiff(img50, img100)
@printf("Percentage difference: %.4f%%\n", d)
| import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public enum ImgDiffPercent {
;
public static void main(String[] args) throws IOException {
BufferedImage img1 = ImageIO.read(new File("Lenna50.jpg"));
BufferedImage img2 = ImageIO.read(new File("Lenna100.jpg"));
double p = getDifferencePercent(img1, img2);
System.out.println("diff percent: " + p);
}
private static double getDifferencePercent(BufferedImage img1, BufferedImage img2) {
int width = img1.getWidth();
int height = img1.getHeight();
int width2 = img2.getWidth();
int height2 = img2.getHeight();
if (width != width2 || height != height2) {
throw new IllegalArgumentException(String.format("Images must have the same dimensions: (%d,%d) vs. (%d,%d)", width, height, width2, height2));
}
long diff = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
diff += pixelDiff(img1.getRGB(x, y), img2.getRGB(x, y));
}
}
long maxDiff = 3L * 255 * width * height;
return 100.0 * diff / maxDiff;
}
private static int pixelDiff(int rgb1, int rgb2) {
int r1 = (rgb1 >> 16) & 0xff;
int g1 = (rgb1 >> 8) & 0xff;
int b1 = rgb1 & 0xff;
int r2 = (rgb2 >> 16) & 0xff;
int g2 = (rgb2 >> 8) & 0xff;
int b2 = rgb2 & 0xff;
return Math.abs(r1 - r2) + Math.abs(g1 - g2) + Math.abs(b1 - b2);
}
}
|
Preserve the algorithm and functionality while converting the code from Julia to Python. | using Images, FileIO, Printf
absdiff(a::RGB{T}, b::RGB{T}) where T = sum(abs(col(a) - col(b)) for col in (red, green, blue))
function pctdiff(A::Matrix{Color{T}}, B::Matrix{Color{T}}) where T
size(A) != size(B) && throw(ArgumentError("images must be same-size"))
s = zero(T)
for (a, b) in zip(A, B)
s += absdiff(a, b)
end
return 100s / 3prod(size(A))
end
img50 = load("data/lenna50.jpg") |> Matrix{RGB{Float64}};
img100 = load("data/lenna100.jpg") |> Matrix{RGB{Float64}};
d = pctdiff(img50, img100)
@printf("Percentage difference: %.4f%%\n", d)
| from PIL import Image
i1 = Image.open("image1.jpg")
i2 = Image.open("image2.jpg")
assert i1.mode == i2.mode, "Different kinds of images."
assert i1.size == i2.size, "Different sizes."
pairs = zip(i1.getdata(), i2.getdata())
if len(i1.getbands()) == 1:
dif = sum(abs(p1-p2) for p1,p2 in pairs)
else:
dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2))
ncomponents = i1.size[0] * i1.size[1] * 3
print ("Difference (percentage):", (dif / 255.0 * 100) / ncomponents)
|
Keep all operations the same but rewrite the snippet in Go. | using Images, FileIO, Printf
absdiff(a::RGB{T}, b::RGB{T}) where T = sum(abs(col(a) - col(b)) for col in (red, green, blue))
function pctdiff(A::Matrix{Color{T}}, B::Matrix{Color{T}}) where T
size(A) != size(B) && throw(ArgumentError("images must be same-size"))
s = zero(T)
for (a, b) in zip(A, B)
s += absdiff(a, b)
end
return 100s / 3prod(size(A))
end
img50 = load("data/lenna50.jpg") |> Matrix{RGB{Float64}};
img100 = load("data/lenna100.jpg") |> Matrix{RGB{Float64}};
d = pctdiff(img50, img100)
@printf("Percentage difference: %.4f%%\n", d)
| package main
import (
"fmt"
"image/jpeg"
"os"
"log"
"image"
)
func loadJpeg(filename string) (image.Image, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
img, err := jpeg.Decode(f)
if err != nil {
return nil, err
}
return img, nil
}
func diff(a, b uint32) int64 {
if a > b {
return int64(a - b)
}
return int64(b - a)
}
func main() {
i50, err := loadJpeg("Lenna50.jpg")
if err != nil {
log.Fatal(err)
}
i100, err := loadJpeg("Lenna100.jpg")
if err != nil {
log.Fatal(err)
}
if i50.ColorModel() != i100.ColorModel() {
log.Fatal("different color models")
}
b := i50.Bounds()
if !b.Eq(i100.Bounds()) {
log.Fatal("different image sizes")
}
var sum int64
for y := b.Min.Y; y < b.Max.Y; y++ {
for x := b.Min.X; x < b.Max.X; x++ {
r1, g1, b1, _ := i50.At(x, y).RGBA()
r2, g2, b2, _ := i100.At(x, y).RGBA()
sum += diff(r1, r2)
sum += diff(g1, g2)
sum += diff(b1, b2)
}
}
nPixels := (b.Max.X - b.Min.X) * (b.Max.Y - b.Min.Y)
fmt.Printf("Image difference: %f%%\n",
float64(sum*100)/(float64(nPixels)*0xffff*3))
}
|
Keep all operations the same but rewrite the snippet in C. | Bitmap.loadPPM = function(self, filename)
local fp = io.open( filename, "rb" )
if fp == nil then return false end
local head, width, height, depth, tail = fp:read("*line", "*number", "*number", "*number", "*line")
self.width, self.height = width, height
self:alloc()
self:clear( {0,0,0} )
for y = 1, self.height do
for x = 1, self.width do
self.pixels[y][x] = { string.byte(fp:read(1)), string.byte(fp:read(1)), string.byte(fp:read(1)) }
end
end
fp:close()
return true
end
Bitmap.percentageDifference = function(self, other)
if self.width ~= other.width or self.height ~= other.height then return end
local dif, abs, spx, opx = 0, math.abs, self.pixels, other.pixels
for y = 1, self.height do
for x = 1, self.width do
local sp, op = spx[y][x], opx[y][x]
dif = dif + abs(sp[1]-op[1]) + abs(sp[2]-op[2]) + abs(sp[3]-op[3])
end
end
return dif/255/self.width/self.height/3*100
end
local bm50 = Bitmap(0,0)
bm50:loadPPM("Lenna50.ppm")
local bm100 = Bitmap(0,0)
bm100:loadPPM("Lenna100.ppm")
print("%diff:", bm100:percentageDifference(bm50))
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define RED_C 0
#define GREEN_C 1
#define BLUE_C 2
#define GET_PIXEL(IMG, X, Y) ((IMG)->buf[ (Y) * (IMG)->width + (X) ])
int main(int argc, char **argv)
{
image im1, im2;
double totalDiff = 0.0;
unsigned int x, y;
if ( argc < 3 )
{
fprintf(stderr, "usage:\n%s FILE1 FILE2\n", argv[0]);
exit(1);
}
im1 = read_image(argv[1]);
if ( im1 == NULL ) exit(1);
im2 = read_image(argv[2]);
if ( im2 == NULL ) { free_img(im1); exit(1); }
if ( (im1->width != im2->width) || (im1->height != im2->height) )
{
fprintf(stderr, "width/height of the images must match!\n");
} else {
for(x=0; x < im1->width; x++)
{
for(y=0; y < im1->width; y++)
{
totalDiff += fabs( GET_PIXEL(im1, x, y)[RED_C] - GET_PIXEL(im2, x, y)[RED_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[GREEN_C] - GET_PIXEL(im2, x, y)[GREEN_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[BLUE_C] - GET_PIXEL(im2, x, y)[BLUE_C] ) / 255.0;
}
}
printf("%lf\n", 100.0 * totalDiff / (double)(im1->width * im1->height * 3) );
}
free_img(im1);
free_img(im2);
}
|
Port the following code from Lua to C# with equivalent syntax and logic. | Bitmap.loadPPM = function(self, filename)
local fp = io.open( filename, "rb" )
if fp == nil then return false end
local head, width, height, depth, tail = fp:read("*line", "*number", "*number", "*number", "*line")
self.width, self.height = width, height
self:alloc()
self:clear( {0,0,0} )
for y = 1, self.height do
for x = 1, self.width do
self.pixels[y][x] = { string.byte(fp:read(1)), string.byte(fp:read(1)), string.byte(fp:read(1)) }
end
end
fp:close()
return true
end
Bitmap.percentageDifference = function(self, other)
if self.width ~= other.width or self.height ~= other.height then return end
local dif, abs, spx, opx = 0, math.abs, self.pixels, other.pixels
for y = 1, self.height do
for x = 1, self.width do
local sp, op = spx[y][x], opx[y][x]
dif = dif + abs(sp[1]-op[1]) + abs(sp[2]-op[2]) + abs(sp[3]-op[3])
end
end
return dif/255/self.width/self.height/3*100
end
local bm50 = Bitmap(0,0)
bm50:loadPPM("Lenna50.ppm")
local bm100 = Bitmap(0,0)
bm100:loadPPM("Lenna100.ppm")
print("%diff:", bm100:percentageDifference(bm50))
| using System;
using System.Drawing;
class Program
{
static void Main()
{
Bitmap img1 = new Bitmap("Lenna50.jpg");
Bitmap img2 = new Bitmap("Lenna100.jpg");
if (img1.Size != img2.Size)
{
Console.Error.WriteLine("Images are of different sizes");
return;
}
float diff = 0;
for (int y = 0; y < img1.Height; y++)
{
for (int x = 0; x < img1.Width; x++)
{
Color pixel1 = img1.GetPixel(x, y);
Color pixel2 = img2.GetPixel(x, y);
diff += Math.Abs(pixel1.R - pixel2.R);
diff += Math.Abs(pixel1.G - pixel2.G);
diff += Math.Abs(pixel1.B - pixel2.B);
}
}
Console.WriteLine("diff: {0} %", 100 * (diff / 255) / (img1.Width * img1.Height * 3));
}
}
|
Translate the given Lua code snippet into C++ without altering its behavior. | Bitmap.loadPPM = function(self, filename)
local fp = io.open( filename, "rb" )
if fp == nil then return false end
local head, width, height, depth, tail = fp:read("*line", "*number", "*number", "*number", "*line")
self.width, self.height = width, height
self:alloc()
self:clear( {0,0,0} )
for y = 1, self.height do
for x = 1, self.width do
self.pixels[y][x] = { string.byte(fp:read(1)), string.byte(fp:read(1)), string.byte(fp:read(1)) }
end
end
fp:close()
return true
end
Bitmap.percentageDifference = function(self, other)
if self.width ~= other.width or self.height ~= other.height then return end
local dif, abs, spx, opx = 0, math.abs, self.pixels, other.pixels
for y = 1, self.height do
for x = 1, self.width do
local sp, op = spx[y][x], opx[y][x]
dif = dif + abs(sp[1]-op[1]) + abs(sp[2]-op[2]) + abs(sp[3]-op[3])
end
end
return dif/255/self.width/self.height/3*100
end
local bm50 = Bitmap(0,0)
bm50:loadPPM("Lenna50.ppm")
local bm100 = Bitmap(0,0)
bm100:loadPPM("Lenna100.ppm")
print("%diff:", bm100:percentageDifference(bm50))
| #include <QImage>
#include <cstdlib>
#include <QColor>
#include <iostream>
int main( int argc , char *argv[ ] ) {
if ( argc != 3 ) {
std::cout << "Call this with imagecompare <file of image 1>"
<< " <file of image 2>\n" ;
return 1 ;
}
QImage firstImage ( argv[ 1 ] ) ;
QImage secondImage ( argv[ 2 ] ) ;
double totaldiff = 0.0 ;
int h = firstImage.height( ) ;
int w = firstImage.width( ) ;
int hsecond = secondImage.height( ) ;
int wsecond = secondImage.width( ) ;
if ( w != wsecond || h != hsecond ) {
std::cerr << "Error, pictures must have identical dimensions!\n" ;
return 2 ;
}
for ( int y = 0 ; y < h ; y++ ) {
uint *firstLine = ( uint* )firstImage.scanLine( y ) ;
uint *secondLine = ( uint* )secondImage.scanLine( y ) ;
for ( int x = 0 ; x < w ; x++ ) {
uint pixelFirst = firstLine[ x ] ;
int rFirst = qRed( pixelFirst ) ;
int gFirst = qGreen( pixelFirst ) ;
int bFirst = qBlue( pixelFirst ) ;
uint pixelSecond = secondLine[ x ] ;
int rSecond = qRed( pixelSecond ) ;
int gSecond = qGreen( pixelSecond ) ;
int bSecond = qBlue( pixelSecond ) ;
totaldiff += std::abs( rFirst - rSecond ) / 255.0 ;
totaldiff += std::abs( gFirst - gSecond ) / 255.0 ;
totaldiff += std::abs( bFirst -bSecond ) / 255.0 ;
}
}
std::cout << "The difference of the two pictures is " <<
(totaldiff * 100) / (w * h * 3) << " % !\n" ;
return 0 ;
}
|
Port the following code from Lua to Java with equivalent syntax and logic. | Bitmap.loadPPM = function(self, filename)
local fp = io.open( filename, "rb" )
if fp == nil then return false end
local head, width, height, depth, tail = fp:read("*line", "*number", "*number", "*number", "*line")
self.width, self.height = width, height
self:alloc()
self:clear( {0,0,0} )
for y = 1, self.height do
for x = 1, self.width do
self.pixels[y][x] = { string.byte(fp:read(1)), string.byte(fp:read(1)), string.byte(fp:read(1)) }
end
end
fp:close()
return true
end
Bitmap.percentageDifference = function(self, other)
if self.width ~= other.width or self.height ~= other.height then return end
local dif, abs, spx, opx = 0, math.abs, self.pixels, other.pixels
for y = 1, self.height do
for x = 1, self.width do
local sp, op = spx[y][x], opx[y][x]
dif = dif + abs(sp[1]-op[1]) + abs(sp[2]-op[2]) + abs(sp[3]-op[3])
end
end
return dif/255/self.width/self.height/3*100
end
local bm50 = Bitmap(0,0)
bm50:loadPPM("Lenna50.ppm")
local bm100 = Bitmap(0,0)
bm100:loadPPM("Lenna100.ppm")
print("%diff:", bm100:percentageDifference(bm50))
| import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public enum ImgDiffPercent {
;
public static void main(String[] args) throws IOException {
BufferedImage img1 = ImageIO.read(new File("Lenna50.jpg"));
BufferedImage img2 = ImageIO.read(new File("Lenna100.jpg"));
double p = getDifferencePercent(img1, img2);
System.out.println("diff percent: " + p);
}
private static double getDifferencePercent(BufferedImage img1, BufferedImage img2) {
int width = img1.getWidth();
int height = img1.getHeight();
int width2 = img2.getWidth();
int height2 = img2.getHeight();
if (width != width2 || height != height2) {
throw new IllegalArgumentException(String.format("Images must have the same dimensions: (%d,%d) vs. (%d,%d)", width, height, width2, height2));
}
long diff = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
diff += pixelDiff(img1.getRGB(x, y), img2.getRGB(x, y));
}
}
long maxDiff = 3L * 255 * width * height;
return 100.0 * diff / maxDiff;
}
private static int pixelDiff(int rgb1, int rgb2) {
int r1 = (rgb1 >> 16) & 0xff;
int g1 = (rgb1 >> 8) & 0xff;
int b1 = rgb1 & 0xff;
int r2 = (rgb2 >> 16) & 0xff;
int g2 = (rgb2 >> 8) & 0xff;
int b2 = rgb2 & 0xff;
return Math.abs(r1 - r2) + Math.abs(g1 - g2) + Math.abs(b1 - b2);
}
}
|
Convert this Lua snippet to Python and keep its semantics consistent. | Bitmap.loadPPM = function(self, filename)
local fp = io.open( filename, "rb" )
if fp == nil then return false end
local head, width, height, depth, tail = fp:read("*line", "*number", "*number", "*number", "*line")
self.width, self.height = width, height
self:alloc()
self:clear( {0,0,0} )
for y = 1, self.height do
for x = 1, self.width do
self.pixels[y][x] = { string.byte(fp:read(1)), string.byte(fp:read(1)), string.byte(fp:read(1)) }
end
end
fp:close()
return true
end
Bitmap.percentageDifference = function(self, other)
if self.width ~= other.width or self.height ~= other.height then return end
local dif, abs, spx, opx = 0, math.abs, self.pixels, other.pixels
for y = 1, self.height do
for x = 1, self.width do
local sp, op = spx[y][x], opx[y][x]
dif = dif + abs(sp[1]-op[1]) + abs(sp[2]-op[2]) + abs(sp[3]-op[3])
end
end
return dif/255/self.width/self.height/3*100
end
local bm50 = Bitmap(0,0)
bm50:loadPPM("Lenna50.ppm")
local bm100 = Bitmap(0,0)
bm100:loadPPM("Lenna100.ppm")
print("%diff:", bm100:percentageDifference(bm50))
| from PIL import Image
i1 = Image.open("image1.jpg")
i2 = Image.open("image2.jpg")
assert i1.mode == i2.mode, "Different kinds of images."
assert i1.size == i2.size, "Different sizes."
pairs = zip(i1.getdata(), i2.getdata())
if len(i1.getbands()) == 1:
dif = sum(abs(p1-p2) for p1,p2 in pairs)
else:
dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2))
ncomponents = i1.size[0] * i1.size[1] * 3
print ("Difference (percentage):", (dif / 255.0 * 100) / ncomponents)
|
Write the same code in Go as shown below in Lua. | Bitmap.loadPPM = function(self, filename)
local fp = io.open( filename, "rb" )
if fp == nil then return false end
local head, width, height, depth, tail = fp:read("*line", "*number", "*number", "*number", "*line")
self.width, self.height = width, height
self:alloc()
self:clear( {0,0,0} )
for y = 1, self.height do
for x = 1, self.width do
self.pixels[y][x] = { string.byte(fp:read(1)), string.byte(fp:read(1)), string.byte(fp:read(1)) }
end
end
fp:close()
return true
end
Bitmap.percentageDifference = function(self, other)
if self.width ~= other.width or self.height ~= other.height then return end
local dif, abs, spx, opx = 0, math.abs, self.pixels, other.pixels
for y = 1, self.height do
for x = 1, self.width do
local sp, op = spx[y][x], opx[y][x]
dif = dif + abs(sp[1]-op[1]) + abs(sp[2]-op[2]) + abs(sp[3]-op[3])
end
end
return dif/255/self.width/self.height/3*100
end
local bm50 = Bitmap(0,0)
bm50:loadPPM("Lenna50.ppm")
local bm100 = Bitmap(0,0)
bm100:loadPPM("Lenna100.ppm")
print("%diff:", bm100:percentageDifference(bm50))
| package main
import (
"fmt"
"image/jpeg"
"os"
"log"
"image"
)
func loadJpeg(filename string) (image.Image, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
img, err := jpeg.Decode(f)
if err != nil {
return nil, err
}
return img, nil
}
func diff(a, b uint32) int64 {
if a > b {
return int64(a - b)
}
return int64(b - a)
}
func main() {
i50, err := loadJpeg("Lenna50.jpg")
if err != nil {
log.Fatal(err)
}
i100, err := loadJpeg("Lenna100.jpg")
if err != nil {
log.Fatal(err)
}
if i50.ColorModel() != i100.ColorModel() {
log.Fatal("different color models")
}
b := i50.Bounds()
if !b.Eq(i100.Bounds()) {
log.Fatal("different image sizes")
}
var sum int64
for y := b.Min.Y; y < b.Max.Y; y++ {
for x := b.Min.X; x < b.Max.X; x++ {
r1, g1, b1, _ := i50.At(x, y).RGBA()
r2, g2, b2, _ := i100.At(x, y).RGBA()
sum += diff(r1, r2)
sum += diff(g1, g2)
sum += diff(b1, b2)
}
}
nPixels := (b.Max.X - b.Min.X) * (b.Max.Y - b.Min.Y)
fmt.Printf("Image difference: %f%%\n",
float64(sum*100)/(float64(nPixels)*0xffff*3))
}
|
Can you help me rewrite this code in C instead of Mathematica, keeping it the same logically? | img50 = ImageData@Import[NotebookDirectory[] <> "Lenna50.jpg"];
img100 = ImageData@Import[NotebookDirectory[] <> "Lenna100.jpg"];
diff = img50 - img100;
Print["Total Difference between both Lenas = ",
Total@Abs@Flatten@diff/Times @@ Dimensions@img50*100, "%"]
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define RED_C 0
#define GREEN_C 1
#define BLUE_C 2
#define GET_PIXEL(IMG, X, Y) ((IMG)->buf[ (Y) * (IMG)->width + (X) ])
int main(int argc, char **argv)
{
image im1, im2;
double totalDiff = 0.0;
unsigned int x, y;
if ( argc < 3 )
{
fprintf(stderr, "usage:\n%s FILE1 FILE2\n", argv[0]);
exit(1);
}
im1 = read_image(argv[1]);
if ( im1 == NULL ) exit(1);
im2 = read_image(argv[2]);
if ( im2 == NULL ) { free_img(im1); exit(1); }
if ( (im1->width != im2->width) || (im1->height != im2->height) )
{
fprintf(stderr, "width/height of the images must match!\n");
} else {
for(x=0; x < im1->width; x++)
{
for(y=0; y < im1->width; y++)
{
totalDiff += fabs( GET_PIXEL(im1, x, y)[RED_C] - GET_PIXEL(im2, x, y)[RED_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[GREEN_C] - GET_PIXEL(im2, x, y)[GREEN_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[BLUE_C] - GET_PIXEL(im2, x, y)[BLUE_C] ) / 255.0;
}
}
printf("%lf\n", 100.0 * totalDiff / (double)(im1->width * im1->height * 3) );
}
free_img(im1);
free_img(im2);
}
|
Generate an equivalent C# version of this Mathematica code. | img50 = ImageData@Import[NotebookDirectory[] <> "Lenna50.jpg"];
img100 = ImageData@Import[NotebookDirectory[] <> "Lenna100.jpg"];
diff = img50 - img100;
Print["Total Difference between both Lenas = ",
Total@Abs@Flatten@diff/Times @@ Dimensions@img50*100, "%"]
| using System;
using System.Drawing;
class Program
{
static void Main()
{
Bitmap img1 = new Bitmap("Lenna50.jpg");
Bitmap img2 = new Bitmap("Lenna100.jpg");
if (img1.Size != img2.Size)
{
Console.Error.WriteLine("Images are of different sizes");
return;
}
float diff = 0;
for (int y = 0; y < img1.Height; y++)
{
for (int x = 0; x < img1.Width; x++)
{
Color pixel1 = img1.GetPixel(x, y);
Color pixel2 = img2.GetPixel(x, y);
diff += Math.Abs(pixel1.R - pixel2.R);
diff += Math.Abs(pixel1.G - pixel2.G);
diff += Math.Abs(pixel1.B - pixel2.B);
}
}
Console.WriteLine("diff: {0} %", 100 * (diff / 255) / (img1.Width * img1.Height * 3));
}
}
|
Produce a functionally identical C++ code for the snippet given in Mathematica. | img50 = ImageData@Import[NotebookDirectory[] <> "Lenna50.jpg"];
img100 = ImageData@Import[NotebookDirectory[] <> "Lenna100.jpg"];
diff = img50 - img100;
Print["Total Difference between both Lenas = ",
Total@Abs@Flatten@diff/Times @@ Dimensions@img50*100, "%"]
| #include <QImage>
#include <cstdlib>
#include <QColor>
#include <iostream>
int main( int argc , char *argv[ ] ) {
if ( argc != 3 ) {
std::cout << "Call this with imagecompare <file of image 1>"
<< " <file of image 2>\n" ;
return 1 ;
}
QImage firstImage ( argv[ 1 ] ) ;
QImage secondImage ( argv[ 2 ] ) ;
double totaldiff = 0.0 ;
int h = firstImage.height( ) ;
int w = firstImage.width( ) ;
int hsecond = secondImage.height( ) ;
int wsecond = secondImage.width( ) ;
if ( w != wsecond || h != hsecond ) {
std::cerr << "Error, pictures must have identical dimensions!\n" ;
return 2 ;
}
for ( int y = 0 ; y < h ; y++ ) {
uint *firstLine = ( uint* )firstImage.scanLine( y ) ;
uint *secondLine = ( uint* )secondImage.scanLine( y ) ;
for ( int x = 0 ; x < w ; x++ ) {
uint pixelFirst = firstLine[ x ] ;
int rFirst = qRed( pixelFirst ) ;
int gFirst = qGreen( pixelFirst ) ;
int bFirst = qBlue( pixelFirst ) ;
uint pixelSecond = secondLine[ x ] ;
int rSecond = qRed( pixelSecond ) ;
int gSecond = qGreen( pixelSecond ) ;
int bSecond = qBlue( pixelSecond ) ;
totaldiff += std::abs( rFirst - rSecond ) / 255.0 ;
totaldiff += std::abs( gFirst - gSecond ) / 255.0 ;
totaldiff += std::abs( bFirst -bSecond ) / 255.0 ;
}
}
std::cout << "The difference of the two pictures is " <<
(totaldiff * 100) / (w * h * 3) << " % !\n" ;
return 0 ;
}
|
Can you help me rewrite this code in Java instead of Mathematica, keeping it the same logically? | img50 = ImageData@Import[NotebookDirectory[] <> "Lenna50.jpg"];
img100 = ImageData@Import[NotebookDirectory[] <> "Lenna100.jpg"];
diff = img50 - img100;
Print["Total Difference between both Lenas = ",
Total@Abs@Flatten@diff/Times @@ Dimensions@img50*100, "%"]
| import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public enum ImgDiffPercent {
;
public static void main(String[] args) throws IOException {
BufferedImage img1 = ImageIO.read(new File("Lenna50.jpg"));
BufferedImage img2 = ImageIO.read(new File("Lenna100.jpg"));
double p = getDifferencePercent(img1, img2);
System.out.println("diff percent: " + p);
}
private static double getDifferencePercent(BufferedImage img1, BufferedImage img2) {
int width = img1.getWidth();
int height = img1.getHeight();
int width2 = img2.getWidth();
int height2 = img2.getHeight();
if (width != width2 || height != height2) {
throw new IllegalArgumentException(String.format("Images must have the same dimensions: (%d,%d) vs. (%d,%d)", width, height, width2, height2));
}
long diff = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
diff += pixelDiff(img1.getRGB(x, y), img2.getRGB(x, y));
}
}
long maxDiff = 3L * 255 * width * height;
return 100.0 * diff / maxDiff;
}
private static int pixelDiff(int rgb1, int rgb2) {
int r1 = (rgb1 >> 16) & 0xff;
int g1 = (rgb1 >> 8) & 0xff;
int b1 = rgb1 & 0xff;
int r2 = (rgb2 >> 16) & 0xff;
int g2 = (rgb2 >> 8) & 0xff;
int b2 = rgb2 & 0xff;
return Math.abs(r1 - r2) + Math.abs(g1 - g2) + Math.abs(b1 - b2);
}
}
|
Change the programming language of this snippet from Mathematica to Python without modifying what it does. | img50 = ImageData@Import[NotebookDirectory[] <> "Lenna50.jpg"];
img100 = ImageData@Import[NotebookDirectory[] <> "Lenna100.jpg"];
diff = img50 - img100;
Print["Total Difference between both Lenas = ",
Total@Abs@Flatten@diff/Times @@ Dimensions@img50*100, "%"]
| from PIL import Image
i1 = Image.open("image1.jpg")
i2 = Image.open("image2.jpg")
assert i1.mode == i2.mode, "Different kinds of images."
assert i1.size == i2.size, "Different sizes."
pairs = zip(i1.getdata(), i2.getdata())
if len(i1.getbands()) == 1:
dif = sum(abs(p1-p2) for p1,p2 in pairs)
else:
dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2))
ncomponents = i1.size[0] * i1.size[1] * 3
print ("Difference (percentage):", (dif / 255.0 * 100) / ncomponents)
|
Rewrite the snippet below in Go so it works the same as the original Mathematica code. | img50 = ImageData@Import[NotebookDirectory[] <> "Lenna50.jpg"];
img100 = ImageData@Import[NotebookDirectory[] <> "Lenna100.jpg"];
diff = img50 - img100;
Print["Total Difference between both Lenas = ",
Total@Abs@Flatten@diff/Times @@ Dimensions@img50*100, "%"]
| package main
import (
"fmt"
"image/jpeg"
"os"
"log"
"image"
)
func loadJpeg(filename string) (image.Image, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
img, err := jpeg.Decode(f)
if err != nil {
return nil, err
}
return img, nil
}
func diff(a, b uint32) int64 {
if a > b {
return int64(a - b)
}
return int64(b - a)
}
func main() {
i50, err := loadJpeg("Lenna50.jpg")
if err != nil {
log.Fatal(err)
}
i100, err := loadJpeg("Lenna100.jpg")
if err != nil {
log.Fatal(err)
}
if i50.ColorModel() != i100.ColorModel() {
log.Fatal("different color models")
}
b := i50.Bounds()
if !b.Eq(i100.Bounds()) {
log.Fatal("different image sizes")
}
var sum int64
for y := b.Min.Y; y < b.Max.Y; y++ {
for x := b.Min.X; x < b.Max.X; x++ {
r1, g1, b1, _ := i50.At(x, y).RGBA()
r2, g2, b2, _ := i100.At(x, y).RGBA()
sum += diff(r1, r2)
sum += diff(g1, g2)
sum += diff(b1, b2)
}
}
nPixels := (b.Max.X - b.Min.X) * (b.Max.Y - b.Min.Y)
fmt.Printf("Image difference: %f%%\n",
float64(sum*100)/(float64(nPixels)*0xffff*3))
}
|
Translate this program into C but keep the logic exactly as in MATLAB. |
function p = PercentageDifferenceBetweenImages(im1,im2)
if numel(im1)~=numel(im2),
error('Error: images have to be the same size');
end
d = abs(single(im1) - single(im2))./255;
p = sum(d(:))./numel(im1)*100;
disp(['Percentage difference between images is: ', num2str(p), '
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define RED_C 0
#define GREEN_C 1
#define BLUE_C 2
#define GET_PIXEL(IMG, X, Y) ((IMG)->buf[ (Y) * (IMG)->width + (X) ])
int main(int argc, char **argv)
{
image im1, im2;
double totalDiff = 0.0;
unsigned int x, y;
if ( argc < 3 )
{
fprintf(stderr, "usage:\n%s FILE1 FILE2\n", argv[0]);
exit(1);
}
im1 = read_image(argv[1]);
if ( im1 == NULL ) exit(1);
im2 = read_image(argv[2]);
if ( im2 == NULL ) { free_img(im1); exit(1); }
if ( (im1->width != im2->width) || (im1->height != im2->height) )
{
fprintf(stderr, "width/height of the images must match!\n");
} else {
for(x=0; x < im1->width; x++)
{
for(y=0; y < im1->width; y++)
{
totalDiff += fabs( GET_PIXEL(im1, x, y)[RED_C] - GET_PIXEL(im2, x, y)[RED_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[GREEN_C] - GET_PIXEL(im2, x, y)[GREEN_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[BLUE_C] - GET_PIXEL(im2, x, y)[BLUE_C] ) / 255.0;
}
}
printf("%lf\n", 100.0 * totalDiff / (double)(im1->width * im1->height * 3) );
}
free_img(im1);
free_img(im2);
}
|
Change the programming language of this snippet from MATLAB to C# without modifying what it does. |
function p = PercentageDifferenceBetweenImages(im1,im2)
if numel(im1)~=numel(im2),
error('Error: images have to be the same size');
end
d = abs(single(im1) - single(im2))./255;
p = sum(d(:))./numel(im1)*100;
disp(['Percentage difference between images is: ', num2str(p), '
| using System;
using System.Drawing;
class Program
{
static void Main()
{
Bitmap img1 = new Bitmap("Lenna50.jpg");
Bitmap img2 = new Bitmap("Lenna100.jpg");
if (img1.Size != img2.Size)
{
Console.Error.WriteLine("Images are of different sizes");
return;
}
float diff = 0;
for (int y = 0; y < img1.Height; y++)
{
for (int x = 0; x < img1.Width; x++)
{
Color pixel1 = img1.GetPixel(x, y);
Color pixel2 = img2.GetPixel(x, y);
diff += Math.Abs(pixel1.R - pixel2.R);
diff += Math.Abs(pixel1.G - pixel2.G);
diff += Math.Abs(pixel1.B - pixel2.B);
}
}
Console.WriteLine("diff: {0} %", 100 * (diff / 255) / (img1.Width * img1.Height * 3));
}
}
|
Please provide an equivalent version of this MATLAB code in C++. |
function p = PercentageDifferenceBetweenImages(im1,im2)
if numel(im1)~=numel(im2),
error('Error: images have to be the same size');
end
d = abs(single(im1) - single(im2))./255;
p = sum(d(:))./numel(im1)*100;
disp(['Percentage difference between images is: ', num2str(p), '
| #include <QImage>
#include <cstdlib>
#include <QColor>
#include <iostream>
int main( int argc , char *argv[ ] ) {
if ( argc != 3 ) {
std::cout << "Call this with imagecompare <file of image 1>"
<< " <file of image 2>\n" ;
return 1 ;
}
QImage firstImage ( argv[ 1 ] ) ;
QImage secondImage ( argv[ 2 ] ) ;
double totaldiff = 0.0 ;
int h = firstImage.height( ) ;
int w = firstImage.width( ) ;
int hsecond = secondImage.height( ) ;
int wsecond = secondImage.width( ) ;
if ( w != wsecond || h != hsecond ) {
std::cerr << "Error, pictures must have identical dimensions!\n" ;
return 2 ;
}
for ( int y = 0 ; y < h ; y++ ) {
uint *firstLine = ( uint* )firstImage.scanLine( y ) ;
uint *secondLine = ( uint* )secondImage.scanLine( y ) ;
for ( int x = 0 ; x < w ; x++ ) {
uint pixelFirst = firstLine[ x ] ;
int rFirst = qRed( pixelFirst ) ;
int gFirst = qGreen( pixelFirst ) ;
int bFirst = qBlue( pixelFirst ) ;
uint pixelSecond = secondLine[ x ] ;
int rSecond = qRed( pixelSecond ) ;
int gSecond = qGreen( pixelSecond ) ;
int bSecond = qBlue( pixelSecond ) ;
totaldiff += std::abs( rFirst - rSecond ) / 255.0 ;
totaldiff += std::abs( gFirst - gSecond ) / 255.0 ;
totaldiff += std::abs( bFirst -bSecond ) / 255.0 ;
}
}
std::cout << "The difference of the two pictures is " <<
(totaldiff * 100) / (w * h * 3) << " % !\n" ;
return 0 ;
}
|
Change the following MATLAB code into Java without altering its purpose. |
function p = PercentageDifferenceBetweenImages(im1,im2)
if numel(im1)~=numel(im2),
error('Error: images have to be the same size');
end
d = abs(single(im1) - single(im2))./255;
p = sum(d(:))./numel(im1)*100;
disp(['Percentage difference between images is: ', num2str(p), '
| import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public enum ImgDiffPercent {
;
public static void main(String[] args) throws IOException {
BufferedImage img1 = ImageIO.read(new File("Lenna50.jpg"));
BufferedImage img2 = ImageIO.read(new File("Lenna100.jpg"));
double p = getDifferencePercent(img1, img2);
System.out.println("diff percent: " + p);
}
private static double getDifferencePercent(BufferedImage img1, BufferedImage img2) {
int width = img1.getWidth();
int height = img1.getHeight();
int width2 = img2.getWidth();
int height2 = img2.getHeight();
if (width != width2 || height != height2) {
throw new IllegalArgumentException(String.format("Images must have the same dimensions: (%d,%d) vs. (%d,%d)", width, height, width2, height2));
}
long diff = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
diff += pixelDiff(img1.getRGB(x, y), img2.getRGB(x, y));
}
}
long maxDiff = 3L * 255 * width * height;
return 100.0 * diff / maxDiff;
}
private static int pixelDiff(int rgb1, int rgb2) {
int r1 = (rgb1 >> 16) & 0xff;
int g1 = (rgb1 >> 8) & 0xff;
int b1 = rgb1 & 0xff;
int r2 = (rgb2 >> 16) & 0xff;
int g2 = (rgb2 >> 8) & 0xff;
int b2 = rgb2 & 0xff;
return Math.abs(r1 - r2) + Math.abs(g1 - g2) + Math.abs(b1 - b2);
}
}
|
Generate a Python translation of this MATLAB snippet without changing its computational steps. |
function p = PercentageDifferenceBetweenImages(im1,im2)
if numel(im1)~=numel(im2),
error('Error: images have to be the same size');
end
d = abs(single(im1) - single(im2))./255;
p = sum(d(:))./numel(im1)*100;
disp(['Percentage difference between images is: ', num2str(p), '
| from PIL import Image
i1 = Image.open("image1.jpg")
i2 = Image.open("image2.jpg")
assert i1.mode == i2.mode, "Different kinds of images."
assert i1.size == i2.size, "Different sizes."
pairs = zip(i1.getdata(), i2.getdata())
if len(i1.getbands()) == 1:
dif = sum(abs(p1-p2) for p1,p2 in pairs)
else:
dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2))
ncomponents = i1.size[0] * i1.size[1] * 3
print ("Difference (percentage):", (dif / 255.0 * 100) / ncomponents)
|
Convert this MATLAB snippet to Go and keep its semantics consistent. |
function p = PercentageDifferenceBetweenImages(im1,im2)
if numel(im1)~=numel(im2),
error('Error: images have to be the same size');
end
d = abs(single(im1) - single(im2))./255;
p = sum(d(:))./numel(im1)*100;
disp(['Percentage difference between images is: ', num2str(p), '
| package main
import (
"fmt"
"image/jpeg"
"os"
"log"
"image"
)
func loadJpeg(filename string) (image.Image, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
img, err := jpeg.Decode(f)
if err != nil {
return nil, err
}
return img, nil
}
func diff(a, b uint32) int64 {
if a > b {
return int64(a - b)
}
return int64(b - a)
}
func main() {
i50, err := loadJpeg("Lenna50.jpg")
if err != nil {
log.Fatal(err)
}
i100, err := loadJpeg("Lenna100.jpg")
if err != nil {
log.Fatal(err)
}
if i50.ColorModel() != i100.ColorModel() {
log.Fatal("different color models")
}
b := i50.Bounds()
if !b.Eq(i100.Bounds()) {
log.Fatal("different image sizes")
}
var sum int64
for y := b.Min.Y; y < b.Max.Y; y++ {
for x := b.Min.X; x < b.Max.X; x++ {
r1, g1, b1, _ := i50.At(x, y).RGBA()
r2, g2, b2, _ := i100.At(x, y).RGBA()
sum += diff(r1, r2)
sum += diff(g1, g2)
sum += diff(b1, b2)
}
}
nPixels := (b.Max.X - b.Min.X) * (b.Max.Y - b.Min.Y)
fmt.Printf("Image difference: %f%%\n",
float64(sum*100)/(float64(nPixels)*0xffff*3))
}
|
Rewrite the snippet below in C so it works the same as the original Nim code. | import strformat
import imageman
var img50, img100: Image[ColorRGBU]
try:
img50 = loadImage[ColorRGBU]("Lenna50.jpg")
img100 = loadImage[ColorRGBU]("Lenna100.jpg")
except IOError:
echo getCurrentExceptionMsg()
quit QuitFailure
let width = img50.width
let height = img50.height
if img100.width != width or img100.height != height:
quit "Images have different sizes.", QuitFailure
var sum = 0
for x in 0..<height:
for y in 0..<width:
let color1 = img50[x, y]
let color2 = img100[x, y]
for i in 0..2:
sum += abs(color1[i].int - color2[i].int)
echo &"Image difference: {sum * 100 / (width * height * 3 * 255):.4f} %"
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define RED_C 0
#define GREEN_C 1
#define BLUE_C 2
#define GET_PIXEL(IMG, X, Y) ((IMG)->buf[ (Y) * (IMG)->width + (X) ])
int main(int argc, char **argv)
{
image im1, im2;
double totalDiff = 0.0;
unsigned int x, y;
if ( argc < 3 )
{
fprintf(stderr, "usage:\n%s FILE1 FILE2\n", argv[0]);
exit(1);
}
im1 = read_image(argv[1]);
if ( im1 == NULL ) exit(1);
im2 = read_image(argv[2]);
if ( im2 == NULL ) { free_img(im1); exit(1); }
if ( (im1->width != im2->width) || (im1->height != im2->height) )
{
fprintf(stderr, "width/height of the images must match!\n");
} else {
for(x=0; x < im1->width; x++)
{
for(y=0; y < im1->width; y++)
{
totalDiff += fabs( GET_PIXEL(im1, x, y)[RED_C] - GET_PIXEL(im2, x, y)[RED_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[GREEN_C] - GET_PIXEL(im2, x, y)[GREEN_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[BLUE_C] - GET_PIXEL(im2, x, y)[BLUE_C] ) / 255.0;
}
}
printf("%lf\n", 100.0 * totalDiff / (double)(im1->width * im1->height * 3) );
}
free_img(im1);
free_img(im2);
}
|
Rewrite the snippet below in C# so it works the same as the original Nim code. | import strformat
import imageman
var img50, img100: Image[ColorRGBU]
try:
img50 = loadImage[ColorRGBU]("Lenna50.jpg")
img100 = loadImage[ColorRGBU]("Lenna100.jpg")
except IOError:
echo getCurrentExceptionMsg()
quit QuitFailure
let width = img50.width
let height = img50.height
if img100.width != width or img100.height != height:
quit "Images have different sizes.", QuitFailure
var sum = 0
for x in 0..<height:
for y in 0..<width:
let color1 = img50[x, y]
let color2 = img100[x, y]
for i in 0..2:
sum += abs(color1[i].int - color2[i].int)
echo &"Image difference: {sum * 100 / (width * height * 3 * 255):.4f} %"
| using System;
using System.Drawing;
class Program
{
static void Main()
{
Bitmap img1 = new Bitmap("Lenna50.jpg");
Bitmap img2 = new Bitmap("Lenna100.jpg");
if (img1.Size != img2.Size)
{
Console.Error.WriteLine("Images are of different sizes");
return;
}
float diff = 0;
for (int y = 0; y < img1.Height; y++)
{
for (int x = 0; x < img1.Width; x++)
{
Color pixel1 = img1.GetPixel(x, y);
Color pixel2 = img2.GetPixel(x, y);
diff += Math.Abs(pixel1.R - pixel2.R);
diff += Math.Abs(pixel1.G - pixel2.G);
diff += Math.Abs(pixel1.B - pixel2.B);
}
}
Console.WriteLine("diff: {0} %", 100 * (diff / 255) / (img1.Width * img1.Height * 3));
}
}
|
Change the programming language of this snippet from Nim to C++ without modifying what it does. | import strformat
import imageman
var img50, img100: Image[ColorRGBU]
try:
img50 = loadImage[ColorRGBU]("Lenna50.jpg")
img100 = loadImage[ColorRGBU]("Lenna100.jpg")
except IOError:
echo getCurrentExceptionMsg()
quit QuitFailure
let width = img50.width
let height = img50.height
if img100.width != width or img100.height != height:
quit "Images have different sizes.", QuitFailure
var sum = 0
for x in 0..<height:
for y in 0..<width:
let color1 = img50[x, y]
let color2 = img100[x, y]
for i in 0..2:
sum += abs(color1[i].int - color2[i].int)
echo &"Image difference: {sum * 100 / (width * height * 3 * 255):.4f} %"
| #include <QImage>
#include <cstdlib>
#include <QColor>
#include <iostream>
int main( int argc , char *argv[ ] ) {
if ( argc != 3 ) {
std::cout << "Call this with imagecompare <file of image 1>"
<< " <file of image 2>\n" ;
return 1 ;
}
QImage firstImage ( argv[ 1 ] ) ;
QImage secondImage ( argv[ 2 ] ) ;
double totaldiff = 0.0 ;
int h = firstImage.height( ) ;
int w = firstImage.width( ) ;
int hsecond = secondImage.height( ) ;
int wsecond = secondImage.width( ) ;
if ( w != wsecond || h != hsecond ) {
std::cerr << "Error, pictures must have identical dimensions!\n" ;
return 2 ;
}
for ( int y = 0 ; y < h ; y++ ) {
uint *firstLine = ( uint* )firstImage.scanLine( y ) ;
uint *secondLine = ( uint* )secondImage.scanLine( y ) ;
for ( int x = 0 ; x < w ; x++ ) {
uint pixelFirst = firstLine[ x ] ;
int rFirst = qRed( pixelFirst ) ;
int gFirst = qGreen( pixelFirst ) ;
int bFirst = qBlue( pixelFirst ) ;
uint pixelSecond = secondLine[ x ] ;
int rSecond = qRed( pixelSecond ) ;
int gSecond = qGreen( pixelSecond ) ;
int bSecond = qBlue( pixelSecond ) ;
totaldiff += std::abs( rFirst - rSecond ) / 255.0 ;
totaldiff += std::abs( gFirst - gSecond ) / 255.0 ;
totaldiff += std::abs( bFirst -bSecond ) / 255.0 ;
}
}
std::cout << "The difference of the two pictures is " <<
(totaldiff * 100) / (w * h * 3) << " % !\n" ;
return 0 ;
}
|
Ensure the translated Java code behaves exactly like the original Nim snippet. | import strformat
import imageman
var img50, img100: Image[ColorRGBU]
try:
img50 = loadImage[ColorRGBU]("Lenna50.jpg")
img100 = loadImage[ColorRGBU]("Lenna100.jpg")
except IOError:
echo getCurrentExceptionMsg()
quit QuitFailure
let width = img50.width
let height = img50.height
if img100.width != width or img100.height != height:
quit "Images have different sizes.", QuitFailure
var sum = 0
for x in 0..<height:
for y in 0..<width:
let color1 = img50[x, y]
let color2 = img100[x, y]
for i in 0..2:
sum += abs(color1[i].int - color2[i].int)
echo &"Image difference: {sum * 100 / (width * height * 3 * 255):.4f} %"
| import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public enum ImgDiffPercent {
;
public static void main(String[] args) throws IOException {
BufferedImage img1 = ImageIO.read(new File("Lenna50.jpg"));
BufferedImage img2 = ImageIO.read(new File("Lenna100.jpg"));
double p = getDifferencePercent(img1, img2);
System.out.println("diff percent: " + p);
}
private static double getDifferencePercent(BufferedImage img1, BufferedImage img2) {
int width = img1.getWidth();
int height = img1.getHeight();
int width2 = img2.getWidth();
int height2 = img2.getHeight();
if (width != width2 || height != height2) {
throw new IllegalArgumentException(String.format("Images must have the same dimensions: (%d,%d) vs. (%d,%d)", width, height, width2, height2));
}
long diff = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
diff += pixelDiff(img1.getRGB(x, y), img2.getRGB(x, y));
}
}
long maxDiff = 3L * 255 * width * height;
return 100.0 * diff / maxDiff;
}
private static int pixelDiff(int rgb1, int rgb2) {
int r1 = (rgb1 >> 16) & 0xff;
int g1 = (rgb1 >> 8) & 0xff;
int b1 = rgb1 & 0xff;
int r2 = (rgb2 >> 16) & 0xff;
int g2 = (rgb2 >> 8) & 0xff;
int b2 = rgb2 & 0xff;
return Math.abs(r1 - r2) + Math.abs(g1 - g2) + Math.abs(b1 - b2);
}
}
|
Convert this Nim block to Python, preserving its control flow and logic. | import strformat
import imageman
var img50, img100: Image[ColorRGBU]
try:
img50 = loadImage[ColorRGBU]("Lenna50.jpg")
img100 = loadImage[ColorRGBU]("Lenna100.jpg")
except IOError:
echo getCurrentExceptionMsg()
quit QuitFailure
let width = img50.width
let height = img50.height
if img100.width != width or img100.height != height:
quit "Images have different sizes.", QuitFailure
var sum = 0
for x in 0..<height:
for y in 0..<width:
let color1 = img50[x, y]
let color2 = img100[x, y]
for i in 0..2:
sum += abs(color1[i].int - color2[i].int)
echo &"Image difference: {sum * 100 / (width * height * 3 * 255):.4f} %"
| from PIL import Image
i1 = Image.open("image1.jpg")
i2 = Image.open("image2.jpg")
assert i1.mode == i2.mode, "Different kinds of images."
assert i1.size == i2.size, "Different sizes."
pairs = zip(i1.getdata(), i2.getdata())
if len(i1.getbands()) == 1:
dif = sum(abs(p1-p2) for p1,p2 in pairs)
else:
dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2))
ncomponents = i1.size[0] * i1.size[1] * 3
print ("Difference (percentage):", (dif / 255.0 * 100) / ncomponents)
|
Can you help me rewrite this code in Go instead of Nim, keeping it the same logically? | import strformat
import imageman
var img50, img100: Image[ColorRGBU]
try:
img50 = loadImage[ColorRGBU]("Lenna50.jpg")
img100 = loadImage[ColorRGBU]("Lenna100.jpg")
except IOError:
echo getCurrentExceptionMsg()
quit QuitFailure
let width = img50.width
let height = img50.height
if img100.width != width or img100.height != height:
quit "Images have different sizes.", QuitFailure
var sum = 0
for x in 0..<height:
for y in 0..<width:
let color1 = img50[x, y]
let color2 = img100[x, y]
for i in 0..2:
sum += abs(color1[i].int - color2[i].int)
echo &"Image difference: {sum * 100 / (width * height * 3 * 255):.4f} %"
| package main
import (
"fmt"
"image/jpeg"
"os"
"log"
"image"
)
func loadJpeg(filename string) (image.Image, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
img, err := jpeg.Decode(f)
if err != nil {
return nil, err
}
return img, nil
}
func diff(a, b uint32) int64 {
if a > b {
return int64(a - b)
}
return int64(b - a)
}
func main() {
i50, err := loadJpeg("Lenna50.jpg")
if err != nil {
log.Fatal(err)
}
i100, err := loadJpeg("Lenna100.jpg")
if err != nil {
log.Fatal(err)
}
if i50.ColorModel() != i100.ColorModel() {
log.Fatal("different color models")
}
b := i50.Bounds()
if !b.Eq(i100.Bounds()) {
log.Fatal("different image sizes")
}
var sum int64
for y := b.Min.Y; y < b.Max.Y; y++ {
for x := b.Min.X; x < b.Max.X; x++ {
r1, g1, b1, _ := i50.At(x, y).RGBA()
r2, g2, b2, _ := i100.At(x, y).RGBA()
sum += diff(r1, r2)
sum += diff(g1, g2)
sum += diff(b1, b2)
}
}
nPixels := (b.Max.X - b.Min.X) * (b.Max.Y - b.Min.Y)
fmt.Printf("Image difference: %f%%\n",
float64(sum*100)/(float64(nPixels)*0xffff*3))
}
|
Translate this program into C but keep the logic exactly as in OCaml. | #! /usr/bin/env ocaml
#directory "+glMLite/"
#load "jpeg_loader.cma"
#load "bigarray.cma"
open Jpeg_loader
let () =
let img1, width1, height1, col_comp1, color_space1 = load_img (Filename Sys.argv.(1))
and img2, width2, height2, col_comp2, color_space2 = load_img (Filename Sys.argv.(2)) in
assert(width1 = width2);
assert(height1 = height2);
assert(col_comp1 = col_comp2);
assert(color_space1 = color_space2);
let img1 = Bigarray.array3_of_genarray img1
and img2 = Bigarray.array3_of_genarray img2 in
let sum = ref 0.0
and num = ref 0 in
for x=0 to pred width1 do
for y=0 to pred height1 do
for c=0 to pred col_comp1 do
let v1 = float img1.{x,y,c}
and v2 = float img2.{x,y,c} in
let diff = (abs_float (v1 -. v2)) /. 255. in
sum := diff +. !sum;
incr num;
done;
done;
done;
let diff_percent = !sum /. float !num in
Printf.printf " diff: %f percent\n" diff_percent;
;;
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define RED_C 0
#define GREEN_C 1
#define BLUE_C 2
#define GET_PIXEL(IMG, X, Y) ((IMG)->buf[ (Y) * (IMG)->width + (X) ])
int main(int argc, char **argv)
{
image im1, im2;
double totalDiff = 0.0;
unsigned int x, y;
if ( argc < 3 )
{
fprintf(stderr, "usage:\n%s FILE1 FILE2\n", argv[0]);
exit(1);
}
im1 = read_image(argv[1]);
if ( im1 == NULL ) exit(1);
im2 = read_image(argv[2]);
if ( im2 == NULL ) { free_img(im1); exit(1); }
if ( (im1->width != im2->width) || (im1->height != im2->height) )
{
fprintf(stderr, "width/height of the images must match!\n");
} else {
for(x=0; x < im1->width; x++)
{
for(y=0; y < im1->width; y++)
{
totalDiff += fabs( GET_PIXEL(im1, x, y)[RED_C] - GET_PIXEL(im2, x, y)[RED_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[GREEN_C] - GET_PIXEL(im2, x, y)[GREEN_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[BLUE_C] - GET_PIXEL(im2, x, y)[BLUE_C] ) / 255.0;
}
}
printf("%lf\n", 100.0 * totalDiff / (double)(im1->width * im1->height * 3) );
}
free_img(im1);
free_img(im2);
}
|
Generate an equivalent C# version of this OCaml code. | #! /usr/bin/env ocaml
#directory "+glMLite/"
#load "jpeg_loader.cma"
#load "bigarray.cma"
open Jpeg_loader
let () =
let img1, width1, height1, col_comp1, color_space1 = load_img (Filename Sys.argv.(1))
and img2, width2, height2, col_comp2, color_space2 = load_img (Filename Sys.argv.(2)) in
assert(width1 = width2);
assert(height1 = height2);
assert(col_comp1 = col_comp2);
assert(color_space1 = color_space2);
let img1 = Bigarray.array3_of_genarray img1
and img2 = Bigarray.array3_of_genarray img2 in
let sum = ref 0.0
and num = ref 0 in
for x=0 to pred width1 do
for y=0 to pred height1 do
for c=0 to pred col_comp1 do
let v1 = float img1.{x,y,c}
and v2 = float img2.{x,y,c} in
let diff = (abs_float (v1 -. v2)) /. 255. in
sum := diff +. !sum;
incr num;
done;
done;
done;
let diff_percent = !sum /. float !num in
Printf.printf " diff: %f percent\n" diff_percent;
;;
| using System;
using System.Drawing;
class Program
{
static void Main()
{
Bitmap img1 = new Bitmap("Lenna50.jpg");
Bitmap img2 = new Bitmap("Lenna100.jpg");
if (img1.Size != img2.Size)
{
Console.Error.WriteLine("Images are of different sizes");
return;
}
float diff = 0;
for (int y = 0; y < img1.Height; y++)
{
for (int x = 0; x < img1.Width; x++)
{
Color pixel1 = img1.GetPixel(x, y);
Color pixel2 = img2.GetPixel(x, y);
diff += Math.Abs(pixel1.R - pixel2.R);
diff += Math.Abs(pixel1.G - pixel2.G);
diff += Math.Abs(pixel1.B - pixel2.B);
}
}
Console.WriteLine("diff: {0} %", 100 * (diff / 255) / (img1.Width * img1.Height * 3));
}
}
|
Port the following code from OCaml to C++ with equivalent syntax and logic. | #! /usr/bin/env ocaml
#directory "+glMLite/"
#load "jpeg_loader.cma"
#load "bigarray.cma"
open Jpeg_loader
let () =
let img1, width1, height1, col_comp1, color_space1 = load_img (Filename Sys.argv.(1))
and img2, width2, height2, col_comp2, color_space2 = load_img (Filename Sys.argv.(2)) in
assert(width1 = width2);
assert(height1 = height2);
assert(col_comp1 = col_comp2);
assert(color_space1 = color_space2);
let img1 = Bigarray.array3_of_genarray img1
and img2 = Bigarray.array3_of_genarray img2 in
let sum = ref 0.0
and num = ref 0 in
for x=0 to pred width1 do
for y=0 to pred height1 do
for c=0 to pred col_comp1 do
let v1 = float img1.{x,y,c}
and v2 = float img2.{x,y,c} in
let diff = (abs_float (v1 -. v2)) /. 255. in
sum := diff +. !sum;
incr num;
done;
done;
done;
let diff_percent = !sum /. float !num in
Printf.printf " diff: %f percent\n" diff_percent;
;;
| #include <QImage>
#include <cstdlib>
#include <QColor>
#include <iostream>
int main( int argc , char *argv[ ] ) {
if ( argc != 3 ) {
std::cout << "Call this with imagecompare <file of image 1>"
<< " <file of image 2>\n" ;
return 1 ;
}
QImage firstImage ( argv[ 1 ] ) ;
QImage secondImage ( argv[ 2 ] ) ;
double totaldiff = 0.0 ;
int h = firstImage.height( ) ;
int w = firstImage.width( ) ;
int hsecond = secondImage.height( ) ;
int wsecond = secondImage.width( ) ;
if ( w != wsecond || h != hsecond ) {
std::cerr << "Error, pictures must have identical dimensions!\n" ;
return 2 ;
}
for ( int y = 0 ; y < h ; y++ ) {
uint *firstLine = ( uint* )firstImage.scanLine( y ) ;
uint *secondLine = ( uint* )secondImage.scanLine( y ) ;
for ( int x = 0 ; x < w ; x++ ) {
uint pixelFirst = firstLine[ x ] ;
int rFirst = qRed( pixelFirst ) ;
int gFirst = qGreen( pixelFirst ) ;
int bFirst = qBlue( pixelFirst ) ;
uint pixelSecond = secondLine[ x ] ;
int rSecond = qRed( pixelSecond ) ;
int gSecond = qGreen( pixelSecond ) ;
int bSecond = qBlue( pixelSecond ) ;
totaldiff += std::abs( rFirst - rSecond ) / 255.0 ;
totaldiff += std::abs( gFirst - gSecond ) / 255.0 ;
totaldiff += std::abs( bFirst -bSecond ) / 255.0 ;
}
}
std::cout << "The difference of the two pictures is " <<
(totaldiff * 100) / (w * h * 3) << " % !\n" ;
return 0 ;
}
|
Rewrite the snippet below in Java so it works the same as the original OCaml code. | #! /usr/bin/env ocaml
#directory "+glMLite/"
#load "jpeg_loader.cma"
#load "bigarray.cma"
open Jpeg_loader
let () =
let img1, width1, height1, col_comp1, color_space1 = load_img (Filename Sys.argv.(1))
and img2, width2, height2, col_comp2, color_space2 = load_img (Filename Sys.argv.(2)) in
assert(width1 = width2);
assert(height1 = height2);
assert(col_comp1 = col_comp2);
assert(color_space1 = color_space2);
let img1 = Bigarray.array3_of_genarray img1
and img2 = Bigarray.array3_of_genarray img2 in
let sum = ref 0.0
and num = ref 0 in
for x=0 to pred width1 do
for y=0 to pred height1 do
for c=0 to pred col_comp1 do
let v1 = float img1.{x,y,c}
and v2 = float img2.{x,y,c} in
let diff = (abs_float (v1 -. v2)) /. 255. in
sum := diff +. !sum;
incr num;
done;
done;
done;
let diff_percent = !sum /. float !num in
Printf.printf " diff: %f percent\n" diff_percent;
;;
| import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public enum ImgDiffPercent {
;
public static void main(String[] args) throws IOException {
BufferedImage img1 = ImageIO.read(new File("Lenna50.jpg"));
BufferedImage img2 = ImageIO.read(new File("Lenna100.jpg"));
double p = getDifferencePercent(img1, img2);
System.out.println("diff percent: " + p);
}
private static double getDifferencePercent(BufferedImage img1, BufferedImage img2) {
int width = img1.getWidth();
int height = img1.getHeight();
int width2 = img2.getWidth();
int height2 = img2.getHeight();
if (width != width2 || height != height2) {
throw new IllegalArgumentException(String.format("Images must have the same dimensions: (%d,%d) vs. (%d,%d)", width, height, width2, height2));
}
long diff = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
diff += pixelDiff(img1.getRGB(x, y), img2.getRGB(x, y));
}
}
long maxDiff = 3L * 255 * width * height;
return 100.0 * diff / maxDiff;
}
private static int pixelDiff(int rgb1, int rgb2) {
int r1 = (rgb1 >> 16) & 0xff;
int g1 = (rgb1 >> 8) & 0xff;
int b1 = rgb1 & 0xff;
int r2 = (rgb2 >> 16) & 0xff;
int g2 = (rgb2 >> 8) & 0xff;
int b2 = rgb2 & 0xff;
return Math.abs(r1 - r2) + Math.abs(g1 - g2) + Math.abs(b1 - b2);
}
}
|
Preserve the algorithm and functionality while converting the code from OCaml to Python. | #! /usr/bin/env ocaml
#directory "+glMLite/"
#load "jpeg_loader.cma"
#load "bigarray.cma"
open Jpeg_loader
let () =
let img1, width1, height1, col_comp1, color_space1 = load_img (Filename Sys.argv.(1))
and img2, width2, height2, col_comp2, color_space2 = load_img (Filename Sys.argv.(2)) in
assert(width1 = width2);
assert(height1 = height2);
assert(col_comp1 = col_comp2);
assert(color_space1 = color_space2);
let img1 = Bigarray.array3_of_genarray img1
and img2 = Bigarray.array3_of_genarray img2 in
let sum = ref 0.0
and num = ref 0 in
for x=0 to pred width1 do
for y=0 to pred height1 do
for c=0 to pred col_comp1 do
let v1 = float img1.{x,y,c}
and v2 = float img2.{x,y,c} in
let diff = (abs_float (v1 -. v2)) /. 255. in
sum := diff +. !sum;
incr num;
done;
done;
done;
let diff_percent = !sum /. float !num in
Printf.printf " diff: %f percent\n" diff_percent;
;;
| from PIL import Image
i1 = Image.open("image1.jpg")
i2 = Image.open("image2.jpg")
assert i1.mode == i2.mode, "Different kinds of images."
assert i1.size == i2.size, "Different sizes."
pairs = zip(i1.getdata(), i2.getdata())
if len(i1.getbands()) == 1:
dif = sum(abs(p1-p2) for p1,p2 in pairs)
else:
dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2))
ncomponents = i1.size[0] * i1.size[1] * 3
print ("Difference (percentage):", (dif / 255.0 * 100) / ncomponents)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.