开发者

compare two images is same or not

开发者 https://www.devze.com 2023-01-30 11:06 出处:网络
I know how to compare two string is same or not.this is coding for compare two strings TextView t,t1; String s,s1;

I know how to compare two string is same or not.this is coding for compare two strings TextView t,t1;

String s,s1;
s=t.getText().toString();
s1=t1.开发者_开发问答setText().toString();
if(s.equals(s1)){
   t.setText("equal");
}
else{
   t.setText("not equal");
}

i need the coding for compare two images are same or not.please give me early


Check that the height matches, if not return false. Then, check if the width matches, and if not, return false. Then check each pixel until you find one that doesn't match. When you do, return false. If every pixel matches, return true.

Pseudocode

bool imagesAreEqual(Image i1, Image i2)
{
    if (i1.getHeight() != i2.getHeight) return false;
    if (i1.getWidth() != i2.getWidth) return false;

    for (int y = 0; y < i1.getHeight(); ++y)
       for (int x = 0; x < i1.getWidth(); ++x)
            if (i1.getPixel(x, y) != i2.getPixel(x, y)) return false;

    return true;
}

In reality, you probably want to treat the image as a two dimensional array if you can, and just compare bytes. I don't know the Android image API, but getPixel might be slow.


If you want to check if the two images are absolutely equal then get the bytes from both, and compare two arrays with element-by-element check.


Image can be defined as an abstraction of BufferedImage, it just holds header-like information. Before reading the image pixels, compare the images with their sizes.

File f1;
File f2;
Image i1 = ImageIO.read(f1);
Image i2 = ImageIO.read(f2);
if(i1.getHeight() == i2.getHeight
    && i1.getWidth() == i2.getWİdth) {
    BufferedImage b1 = ImageIO.read(f1);
    BufferedImage b2 = ImageIO.read(f2);
    //compare pixels
}

Image is read way more faster than BufferedImage, as it doesn't get pixels from the file. For comparison, I suggest a two or more layered pixels comparison. Using random will boost your speed, as finding a non-matching pixel is enough for you.

for(i=0; i<N; i++) {
    x = r.nextInt(184);
    y = r.nextInt(184);
    if(b1.getRGB(x,y) != b2.getRGB(x,y)) {
        break;
    }
}

If the images pass the randomized comparison, do a pixel by pixel comparison, with breaking the loop in case of finding non-matching pixels. I answered assuming that you need a fast running comparison. For that, I don't suggest MD5 hashing, unless you want to find all duplicate images in a big image directory. If you just want to compare two images, and fast, MD5 don't make much sense, as it's needed to read image's all pixels to checkout a hash value and this decreases speed for one comparison.

0

精彩评论

暂无评论...
验证码 换一张
取 消