Implement Sobel Algorithm [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I want to implement Sobel algorithm.
First
I get gray data of the input image and put data into mGrayData:
BufferedImage mImage, mNewImage;
for (int i = 0; i < mHeight; i++) {
for (int j = 0; j < mWidth; j++) {
int rgb = mImage.getRGB(j, i);
int newRgb;
int r = (rgb >> 16) & 0xff;
int g = (rgb >> 8) & 0xff;
int b = rgb & 0xff;
int grayLevel = (r + g + b) / 3;
int gray = (grayLevel << 16) + (grayLevel << 8) + grayLevel;
mGrayData[i * mWidth + j] = gray;
}
}
Then
I calculate every point's gradient:
int[] gradient = new int[mWidth * mHeight];
for (int x=1;x<mWidth-1;x++){
for (int y=1;y<mHeight-1;y++){
int grayX = getGrayPoint(x+1,y-1)+2*getGrayPoint(x+1,y)+getGrayPoint(x+1,y+1)-
(getGrayPoint(x-1,y-1)+2*getGrayPoint(x-1,y)+getGrayPoint(x-1,y+1));
int grayY = (getGrayPoint(x-1, y+1) + 2*getGrayPoint(x,y+1)+getGrayPoint(x+1,y+1))-
(getGrayPoint(x-1,y-1) + 2*getGrayPoint(x,y-1) + getGrayPoint(x+1,y-1));
gradient[x+y*mWidth] = (int) Math.sqrt(grayX*grayX+grayY*grayY);
}
}
method gradient(x,y):
private int getGrayPoint(int x,int y){
return mGrayData[x+y*mWidth];
}
Problem
input image:
and after be fitered:
Now how can I implement this?
Edit:
I do not know about how to use gradient data.I try this:
int[] gradient = getGradient();
int maxGradient = gradient[0];
for (int i=0;i<gradient.length;i++){
if (gradient[i]>maxGradient)
maxGradient = gradient[i];
}
float scaleFactor = 255.0f / maxGradient;
for (int y = 1; y < mHeight - 1; ++y)
for (int x = 1; x < mWidth - 1; ++x)
if (Math.round(scaleFactor * gradient[y * mWidth + x]) >= mThreshold)
{
mNewImage.setRGB(x, y, 0x000000);
}else {
mNewImage.setRGB(x,y,mGrayData[y * mWidth + x]);
}
File file = new File("D:\\Documents\\Pictures\\engine3.png");
if (!file.exists()) {
file.getParentFile().mkdir();
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
ImageIO.write(mNewImage, "png", file);
} catch (IOException e) {
e.printStackTrace();
}
And I get image:

It seems that you are using wrong data for gradient calculation. Your mGrayData contains integer value 0xAXXX, where A is alpha and X is gray value (computed as average of r,g,b).
Instead use
mGrayData[i * mWidth + j] = average;
2nd edit:
Suggestion:
private int getGrayPoint(int x,int y){
return mGrayData[x+y*mWidth] & 0xff;
}

Related

scrambled block trying to decompress BC1 texture compression

I've been trying to implement a BC1 (DXT1) decompression algorithm in Java. Everything seems to work pretty precise but I've ran into problem with some blocks around transparent ones. I've been trying to resolve it for a few hours without success.
In short, after decompressing all blocks everything looks good except for the blocks whose are around transparent ones. During the development I've been checking results with results from DirectXTex (texconv) which is written in C++.
This is my result compared to DirectXTex one:
Here is the code I'm using:
BufferedImage decompress(byte[] buffer, int width, int height)
and implementation:
BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
int[] scanline = new int[4 * width]; //stores 4 horizontal lines (width/4 blocks)
RGBA[] blockPalette = new RGBA[4]; //stores RGBA values of current block
int bufferOffset = 0;
for (int row = 0; row < height / 4; row++) {
for (int col = 0; col < width / 4; col++) {
short rgb0 = Short.reverseBytes(Bytes.getShort(buffer, bufferOffset));
short rgb1 = Short.reverseBytes(Bytes.getShort(buffer, bufferOffset + 2));
int bitmap = Integer.reverseBytes(Bytes.getInt(buffer, bufferOffset + 4));
bufferOffset += 8;
blockPalette[0] = R5G6B5.decode(rgb0);
blockPalette[1] = R5G6B5.decode(rgb1);
if(rgb0 <= rgb1) {
int c2r = (blockPalette[0].getRed() + blockPalette[1].getRed()) / 2;
int c2g = (blockPalette[0].getGreen() + blockPalette[1].getGreen()) / 2;
int c2b = (blockPalette[0].getBlue() + blockPalette[1].getBlue()) / 2;
blockPalette[2] = new RGBA(c2r, c2g, c2b, 255);
blockPalette[3] = new RGBA(0, 0, 0, 0);
} else {
int c2r = (2 * blockPalette[0].getRed() + blockPalette[1].getRed()) / 3;
int c2g = (2 * blockPalette[0].getGreen() + blockPalette[1].getGreen()) / 3;
int c2b = (2 * blockPalette[0].getBlue() + blockPalette[1].getBlue()) / 3;
int c3r = (blockPalette[0].getRed() + 2 * blockPalette[1].getRed()) / 3;
int c3g = (blockPalette[0].getGreen() + 2 * blockPalette[1].getGreen()) / 3;
int c3b = (blockPalette[0].getBlue() + 2 * blockPalette[1].getBlue()) / 3;
blockPalette[2] = new RGBA(c2r, c2g, c2b, 255);
blockPalette[3] = new RGBA(c3r, c3g, c3b, 255);
}
for (int i = 0; i < 16; i++, bitmap >>= 2) {
int pi = (i / 4) * width + (col * 4 + i % 4);
int index = bitmap & 3;
scanline[pi] = A8R8G8B8.encode(blockPalette[index]);
}
}
//copy scanline to buffered image
result.setRGB(0, row * 4, width, 4, scanline, 0, width);
}
return result;
Does anyone have idea where is the problem? I've been doing exactly the same steps as specification says: Block Compression (Direct3D 10)
Is it that blockPalette[2].set(c2r, c2g, c2b); should be blockPalette[2].set(c2r, c2g, c2b, 255);? (in two locations)
For those who are interested, I've found that the problem was in comparing short values.
I've just changed:
if(rgb0 <= rgb1) {
to either
if(Short.compareUnsigned(rgb0, rgb1) <= 0) {
or
if((rgb0 & 0xffff) <= (rgb1 & 0xffff)) {
and this ensures that color values are compared as unsigned shorts (positive integers).

How to import .java library in IntelliJ (folder of .java files)

I am a new programmer.
Here, I am trying to import a library (com.digitalmodular).
What I want to do is run the java program in here
package demos;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.Arrays;
import com.digitalmodular.utilities.RandomFunctions;
import com.digitalmodular.utilities.gui.ImageFunctions;
import com.digitalmodular.utilities.swing.window.PixelImage;
import com.digitalmodular.utilities.swing.window.PixelWindow;
/**
* #author jeronimus
*/
// Date 2014-02-28
public class AllColorDiffusion extends PixelWindow implements Runnable {
private static final int CHANNEL_BITS = 7;
public static void main(String[] args) {
int bits = CHANNEL_BITS * 3;
int heightBits = bits / 2;
int widthBits = bits - heightBits;
new AllColorDiffusion(CHANNEL_BITS, 1 << widthBits, 1 << heightBits);
}
private final int width;
private final int height;
private final int channelBits;
private final int channelSize;
private PixelImage img;
private javax.swing.Timer timer;
private boolean[] colorCube;
private long[] foundColors;
private boolean[] queued;
private int[] queue;
private int queuePointer = 0;
private int remaining;
public AllColorDiffusion(int channelBits, int width, int height) {
super(1024, 1024 * height / width);
RandomFunctions.RND.setSeed(0);
this.width = width;
this.height = height;
this.channelBits = channelBits;
channelSize = 1 << channelBits;
}
#Override
public void initialized() {
img = new PixelImage(width, height);
colorCube = new boolean[channelSize * channelSize * channelSize];
foundColors = new long[channelSize * channelSize * channelSize];
queued = new boolean[width * height];
queue = new int[width * height];
for (int i = 0; i < queue.length; i++)
queue[i] = i;
new Thread(this).start();
}
#Override
public void resized() {}
#Override
public void run() {
timer = new javax.swing.Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
draw();
}
});
while (true) {
img.clear(0);
init();
render();
}
// System.exit(0);
}
private void init() {
RandomFunctions.RND.setSeed(0);
Arrays.fill(colorCube, false);
Arrays.fill(queued, false);
remaining = width * height;
// Initial seeds (need to be the darkest colors, because of the darkest
// neighbor color search algorithm.)
setPixel(width / 2 + height / 2 * width, 0);
remaining--;
}
private void render() {
timer.start();
for (; remaining > 0; remaining--) {
int point = findPoint();
int color = findColor(point);
setPixel(point, color);
}
timer.stop();
draw();
try {
ImageFunctions.savePNG(System.currentTimeMillis() + ".png", img.image);
}
catch (IOException e1) {
e1.printStackTrace();
}
}
void draw() {
g.drawImage(img.image, 0, 0, getWidth(), getHeight(), 0, 0, width, height, null);
repaintNow();
}
private int findPoint() {
while (true) {
// Time to reshuffle?
if (queuePointer == 0) {
for (int i = queue.length - 1; i > 0; i--) {
int j = RandomFunctions.RND.nextInt(i);
int temp = queue[i];
queue[i] = queue[j];
queue[j] = temp;
queuePointer = queue.length;
}
}
if (queued[queue[--queuePointer]])
return queue[queuePointer];
}
}
private int findColor(int point) {
int x = point & width - 1;
int y = point / width;
// Calculate the reference color as the average of all 8-connected
// colors.
int r = 0;
int g = 0;
int b = 0;
int n = 0;
for (int j = -1; j <= 1; j++) {
for (int i = -1; i <= 1; i++) {
point = (x + i & width - 1) + width * (y + j & height - 1);
if (img.pixels[point] != 0) {
int pixel = img.pixels[point];
r += pixel >> 24 - channelBits & channelSize - 1;
g += pixel >> 16 - channelBits & channelSize - 1;
b += pixel >> 8 - channelBits & channelSize - 1;
n++;
}
}
}
r /= n;
g /= n;
b /= n;
// Find a color that is preferably darker but not too far from the
// original. This algorithm might fail to take some darker colors at the
// start, and when the image is almost done the size will become really
// huge because only bright reference pixels are being searched for.
// This happens with a probability of 50% with 6 channelBits, and more
// with higher channelBits values.
//
// Try incrementally larger distances from reference color.
for (int size = 2; size <= channelSize; size *= 2) {
n = 0;
// Find all colors in a neighborhood from the reference color (-1 if
// already taken).
for (int ri = r - size; ri <= r + size; ri++) {
if (ri < 0 || ri >= channelSize)
continue;
int plane = ri * channelSize * channelSize;
int dr = Math.abs(ri - r);
for (int gi = g - size; gi <= g + size; gi++) {
if (gi < 0 || gi >= channelSize)
continue;
int slice = plane + gi * channelSize;
int drg = Math.max(dr, Math.abs(gi - g));
int mrg = Math.min(ri, gi);
for (int bi = b - size; bi <= b + size; bi++) {
if (bi < 0 || bi >= channelSize)
continue;
if (Math.max(drg, Math.abs(bi - b)) > size)
continue;
if (!colorCube[slice + bi])
foundColors[n++] = Math.min(mrg, bi) << channelBits * 3 | slice + bi;
}
}
}
if (n > 0) {
// Sort by distance from origin.
Arrays.sort(foundColors, 0, n);
// Find a random color amongst all colors equally distant from
// the origin.
int lowest = (int)(foundColors[0] >> channelBits * 3);
for (int i = 1; i < n; i++) {
if (foundColors[i] >> channelBits * 3 > lowest) {
n = i;
break;
}
}
int nextInt = RandomFunctions.RND.nextInt(n);
return (int)(foundColors[nextInt] & (1 << channelBits * 3) - 1);
}
}
return -1;
}
private void setPixel(int point, int color) {
int b = color & channelSize - 1;
int g = color >> channelBits & channelSize - 1;
int r = color >> channelBits * 2 & channelSize - 1;
img.pixels[point] = 0xFF000000 | ((r << 8 | g) << 8 | b) << 8 - channelBits;
colorCube[color] = true;
int x = point & width - 1;
int y = point / width;
queued[point] = false;
for (int j = -1; j <= 1; j++) {
for (int i = -1; i <= 1; i++) {
point = (x + i & width - 1) + width * (y + j & height - 1);
if (img.pixels[point] == 0) {
queued[point] = true;
}
}
}
}
}
The thing is, I cant figure out how to import the library into IntelliJ. I have tried importing the library from Project Structure->Modules->Dependencies->Library->Java but failed. It appears that all the files in the given library are .java files, not .jar files
How should I import the library? Do I need to compile the whole library first? If yes, how?
This is my first question on this site, so my question may not be so clear :P
try
go to project settings -> Platform Settings -> SDKs -> Sourcepath (in the right panel) and add your downloaded zip -> Apply -> OK

Error stated that the program cannot find symbol for hexa2 and hexa4

I'm a beginner to Java programming. I have the algorithm but I'm having trouble to code it. I would like to compare 2 similar images at position 2 and 4 of RGB hexadecimal pixel values to check whether one of the images has different pixel values than the other one.
My Algorithm logic:
if(image1.substring2 == image2.substring2) && (image1.substring4 == image2.substring4), pixels are the same.
if(image1.substring2 != image2.substring2) || (image1.substring4 != image2.substring4), pixels are not the same.
if(image1.substring2 != image2.substring2) && (image1.substring4 != image2.substring4), pixels are not the same.
I have the remaining codes here. I tried to separate all the process so it is easy for me to troubleshoot later.
//MAIN
public class getPixelRGB1
{
private static int a;
private static int r;
private static int g;
private static int b;
private static final double bitPerColor = 4.0;
public static void main(String[] args) throws IOException
{
FileInputStream image = null;
FileInputStream image2 = null;
getPixelData1 newPD = new getPixelData1();
try {
BufferedImage img, img2;
File file = new File("img0.jpg");
File file2 = new File("imgstega.jpg");
image = new FileInputStream(file);
image2 = new FileInputStream(file2);
img = ImageIO.read(image);
img2 = ImageIO.read(image2);
int rowcol;
int width = img.getWidth();
int height = img.getHeight();
System.out.println("Image's Width: " + width);
System.out.println("Image's Height: " + height);
int[][] pixelData = new int[width * height][3];
System.out.println("Pixel Data: " + pixelData);
int[] rgb;
int count = 0;
for(int i=0; i<width; i++)
{
for(int j=0; j<height; j++)
{
rgb = newPD.getPixelData(img, i, j);
for(int k = 0; k < rgb.length; k++)
{
pixelData[count][k] = rgb[k];
}
count++;
System.out.println("\nRGB Counts: " + count);
}
}
int width2 = img2.getWidth();
int height2 = img2.getHeight();
System.out.println("Image's Width: " + width2);
System.out.println("Image's Height: " + height2);
int[][] pixelData2 = new int[width2 * height2][3];
int[] rgb2;
int counter = 0;
for(int i=0; i<width2; i++)
{
for(int j=0; j<height2; j++)
{
rgb2 = newPD.getPixelData(img2, i, j);
for(int k = 0; k < rgb2.length; k++)
{
pixelData2[counter][k] = rgb2[k];
}
counter++;
System.out.println("\nRGB2 Counts: " + counter);
}
}
} catch (FileNotFoundException ex) {
Logger.getLogger(getPixelRGB1.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
image.close();
} catch (IOException ex) {
Logger.getLogger(getPixelRGB1.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
//1ST PROCESS - Get RGB Pixel Values
public class getPixelData1
{
private static final double bitPerColor = 4.0;
public int[] getPixelData(BufferedImage img, int w, int h) throws IOException
{
int argb = img.getRGB(w, h);
int rgb[] = new int[]
{
(argb >> 16) & 0xff, //red
(argb >> 8) & 0xff, //green
(argb ) & 0xff //blue
};
int red = rgb[0];
int green = rgb[1]; //RGB Value in Decimal
int blue = rgb[2];
System.out.println("\nRGBValue in Decimal --> " + "\nRed: " + red + " Green: " + green + " Blue: " + blue);
//Convert each channel RGB to Hexadecimal value
String rHex = Integer.toHexString((int)(red));
String gHex = Integer.toHexString((int)(green));
String bHex = Integer.toHexString((int)(blue));
System.out.println("\nRGBValue in Hexa --> " + "\nRed Green Blue " + rHex + gHex + bHex);
//Check position 2 and 4 of hexa value for any changes
String hexa2, hexa4 = "";
String rgbHexa = rHex + gHex + bHex;
hexa2 = rgbHexa.substring(1,2);
System.out.println("\nString RGB Hexa: " + rgbHexa);
System.out.println("\nSubstring at position 2: " + hexa2);
String hex = String.format("%02X%02X%02X", red, green, blue);
hexa4 = hex.substring(3,4);
System.out.println("\nSubstring at position 4: " + hexa4);
return rgb;
}
}
//2nd Process - to compare the RGB Hex value of both images
public class compareHexaRGB
{
public int[] compareHexaRGB(BufferedImage img, BufferedImage img2, int w, int h) throws IOException
{
getPixelData1 newPD = new getPixelData1(); //get method from class getPixelData1 - is this correct?
if((img.hexa2.equals(img2.hexa2)) && (img.hexa4.equals(img2.hexa4)))
{
System.out.println("Pixel values at position 2 and 4 are the same.");
}
else if((img.hexa2 != img2.hexa2) || (img.hexa4 != img2.hexa4))
{
System.out.println("Pixel values at position 2 and 4 are not the same.");
}
else if((img.hexa2 != img2.hexa2) && (img.hexa4 != img2.hexa4))
{
System.out.println("Pixel values at position 2 and 4 are not the same.");
}
}
}
The error stated that the program cannot find symbol for hexa2 and hexa4 in bufferedImage. Can someone check whether I've done something wrong with my coding here? I'm still new to Java.
img is of type BufferedImage (javadoc). It does not contain any non-private (nor private) fields named hexa2 or hexa4.
What you need to do is to refactor your code to make sure you have access to them in compareHexaRGB(). There are probably many ways this can be done. Perhaps you could extend BufferedImage to include your fields, or perhaps you could just pass them as input to the method.
Which solution that would be the more elegant one is hard to determine given that we don't really have all your code (for example, I don't see compareHexaRGB() being called at all).
To be more precise about the compilation problem: By using img.hexa2 to access a field, you assume that there is a field called hexa2 in BufferedImage that is accessible from your class. This is true if a field for example is declared as public. More typically, the fields are private scoped and need to be accessed by a getter/setter. For BufferedImage, no such field exists at all.
Learn about access control here.

Comparing images to find duplicates

I have a few (38000) picture/video files in a folder. Approximately 40% of these are duplicates which I'm trying to get rid of. My question is, how can I tell if 2 files are identical? So far I tried to use a SHA1 of the files but it turns out that many duplicates files had different hashes. This is the code I was using:
public static String getHash(File doc) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA1");
FileInputStream inStream = new FileInputStream(doc);
DigestInputStream dis = new DigestInputStream(inStream, md);
BufferedInputStream bis = new BufferedInputStream(dis);
while (true) {
int b = bis.read();
if (b == -1)
break;
}
inStream.close();
dis.close();
bis.close();
} catch (NoSuchAlgorithmException | IOException e) {
e.printStackTrace();
}
BigInteger bi = new BigInteger(md.digest());
return bi.toString(16);
}
Can I modify this in any way? Or will I have to use a different method?
As outlined above duplicate detection can be based on a hash. However, if you want to have near duplicate detection, which means that you are searching for images that basically show the same things, but have been scaled, rotated, etc. you might need a content based image retrieval approach. There's LIRE (https://code.google.com/p/lire/), a Java library for that, and you'll find the "SimpleApplication" in the Download section. What you then can do is to
Index the first image
go to the next image I
Search for I in the index
If there are results with a score below a threshold, then mark them as duplicate
Index I
Go to (2)
Students of mine did it, it worked well, but I don't have the source code at hand. But rest assured, it's just a few lines and the simple application will get you started.
Besides using hash, if your duplicates have different sizes (because they were resized), you could compare pixel by pixel (maybe not the entire image but a sub-section of the image).
This may depend on the image format but you could compare by comparing the height and width and then go pixel by pixel using the RGB code. To make it more efficient you can decide a threshold of comparison. For example:
public class Main {
public static void main(String[] args) throws IOException {
ImageChecker i = new ImageChecker();
BufferedImage one = ImageIO.read(new File("D:/Images/460249177.jpg"));
BufferedImage two = ImageIO.read(new File("D:/Images/460249177a.jpg"));
if(one.getWidth() + one.getHeight() >= two.getWidth() + two.getHeight()) {
i.setOne(one);
i.setTwo(two);
} else {
i.setOne(two);
i.setTwo(one);
}
System.out.println(i.compareImages());
}
}
public class ImageChecker {
private BufferedImage one;
private BufferedImage two;
private double difference = 0;
private int x = 0;
private int y = 0;
public ImageChecker() {
}
public boolean compareImages() {
int f = 20;
int w1 = Math.min(50, one.getWidth() - two.getWidth());
int h1 = Math.min(50, one.getHeight() - two.getHeight());
int w2 = Math.min(5, one.getWidth() - two.getWidth());
int h2 = Math.min(5, one.getHeight() - two.getHeight());
for (int i = 0; i <= one.getWidth() - two.getWidth(); i += f) {
for (int j = 0; j <= one.getHeight() - two.getHeight(); j += f) {
compareSubset(i, j, f);
}
}
one = one.getSubimage(Math.max(0, x - w1), Math.max(0, y - h1),
Math.min(two.getWidth() + w1, one.getWidth() - x + w1),
Math.min(two.getHeight() + h1, one.getHeight() - y + h1));
x = 0;
y = 0;
difference = 0;
f = 5;
for (int i = 0; i <= one.getWidth() - two.getWidth(); i += f) {
for (int j = 0; j <= one.getHeight() - two.getHeight(); j += f) {
compareSubset(i, j, f);
}
}
one = one.getSubimage(Math.max(0, x - w2), Math.max(0, y - h2),
Math.min(two.getWidth() + w2, one.getWidth() - x + w2),
Math.min(two.getHeight() + h2, one.getHeight() - y + h2));
f = 1;
for (int i = 0; i <= one.getWidth() - two.getWidth(); i += f) {
for (int j = 0; j <= one.getHeight() - two.getHeight(); j += f) {
compareSubset(i, j, f);
}
}
System.out.println(difference);
return difference < 0.1;
}
public void compareSubset(int a, int b, int f) {
double diff = 0;
for (int i = 0; i < two.getWidth(); i += f) {
for (int j = 0; j < two.getHeight(); j += f) {
int onepx = one.getRGB(i + a, j + b);
int twopx = two.getRGB(i, j);
int r1 = (onepx >> 16);
int g1 = (onepx >> 8) & 0xff;
int b1 = (onepx) & 0xff;
int r2 = (twopx >> 16);
int g2 = (twopx >> 8) & 0xff;
int b2 = (twopx) & 0xff;
diff += (Math.abs(r1 - r2) + Math.abs(g1 - g2) + Math.abs(b1
- b2)) / 3.0 / 255.0;
}
}
double percentDiff = diff * f * f / (two.getWidth() * two.getHeight());
if (percentDiff < difference || difference == 0) {
difference = percentDiff;
x = a;
y = b;
}
}
public BufferedImage getOne() {
return one;
}
public void setOne(BufferedImage one) {
this.one = one;
}
public BufferedImage getTwo() {
return two;
}
public void setTwo(BufferedImage two) {
this.two = two;
}
}
You need to use aHash, pHash and best of both dHash algorithm for this.
I wrote a pure java library just for this few days back. You can feed it with directory path(includes sub-directory), and it will list the duplicate images in list with absolute path which you want to delete. Alternatively, you can use it to find all unique images in a directory too.
It used awt api internally, so can't be used for Android though. Since, imageIO has problem reading alot of new types of images, i am using twelve monkeys jar which is internally used.
https://github.com/srch07/Duplicate-Image-Finder-API
Jar with dependencies bundled internally can be downloaded from, https://github.com/srch07/Duplicate-Image-Finder-API/blob/master/archives/duplicate_image_finder_1.0.jar
The api can find duplicates among images of different sizes too.
You could convert your files with e.g. imagemagick convert to a format which has a canonical representation and as little metadata as possible. I guess I'd use PNM. So try something like this:
convert input.png pnm:- | md5sum -
If this does yield the same result for two files which compared different before, then metadata is in fact the source of your problem, and you can either use some command line approach like this, or update your code to read the image and compute the hash from the raw uncompressed data.
If, on the other hand, different files still compare different, then you have some changes to the actual image data. One possible cause might be the addition or removal of an alpha channel, particularly if you are dealing with PNG here. With JPEG, on the other hand, you'll likely have images uncompressed and then recompressed again, which will lead to slight modifications and data loss. JPEG is an inherently lossy codec, and any two images will likely differ unless they were created using the same application (or library), with the same settings and from the same input data. In that case you'll need to perform a fuzzy image matching. Tools like Geeqie can perform such things. If you want to do this yourself, you'll have a lot of work ahead of you, and should do some research up front.
It's been a long time so I should probably explain how I finally solved my problem. The real trick was to not use hashes to begin with and instead just compare the timestamps in the exif data. Given that these pictures were taken either by me of my wife it would have been quite unlikely for different files to have the same timestamp, hence this simpler solution was actually much more reliable.
You can check different percentage of two images through below method and if different percentage os below 10 then you can call it identical image:
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);
}
// covert image to Buffered image through this method
public static BufferedImage toBufferedImage(Image img)
{
if (img instanceof BufferedImage)
{
return (BufferedImage) img;
}
// Create a buffered image with transparency
BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
// Draw the image on to the buffered image
Graphics2D bGr = bimage.createGraphics();
bGr.drawImage(img, 0, 0, null);
bGr.dispose();
// Return the buffered image
return bimage;
}
Get insight idea from this site : https://rosettacode.org/wiki/Percentage_difference_between_images#Kotlin
The question was asked long time ago. I have found the following link very useful, it has codes for all languages. https://rosettacode.org/wiki/Percentage_difference_between_images#Kotlin
Here is the code for Kotlin taken from the link
import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.ImageIO
import kotlin.math.abs
fun getDifferencePercent(img1: BufferedImage, img2: BufferedImage): Double {
val width = img1.width
val height = img1.height
val width2 = img2.width
val height2 = img2.height
if (width != width2 || height != height2) {
val f = "(%d,%d) vs. (%d,%d)".format(width, height, width2, height2)
throw IllegalArgumentException("Images must have the same dimensions: $f")
}
var diff = 0L
for (y in 0 until height) {
for (x in 0 until width) {
diff += pixelDiff(img1.getRGB(x, y), img2.getRGB(x, y))
}
}
val maxDiff = 3L * 255 * width * height
return 100.0 * diff / maxDiff
}
fun pixelDiff(rgb1: Int, rgb2: Int): Int {
val r1 = (rgb1 shr 16) and 0xff
val g1 = (rgb1 shr 8) and 0xff
val b1 = rgb1 and 0xff
val r2 = (rgb2 shr 16) and 0xff
val g2 = (rgb2 shr 8) and 0xff
val b2 = rgb2 and 0xff
return abs(r1 - r2) + abs(g1 - g2) + abs(b1 - b2)
}
fun main(args: Array<String>) {
val img1 = ImageIO.read(File("Lenna50.jpg"))
val img2 = ImageIO.read(File("Lenna100.jpg"))
val p = getDifferencePercent(img1, img2)
println("The percentage difference is ${"%.6f".format(p)}%")
}

scanning an image for a specific color in java [duplicate]

This question already has an answer here:
How to scan the screen for a specific color/image in java?
(1 answer)
Closed 9 years ago.
I'm not sure where to start on this one, but is there a way I can use Java to scan an image row by row for a specific color, and pass all of the positions into and ArrayList?
Can you? yes. Here's how:
ArrayList<Point> list = new ArrayList<Point>();
BufferedImage bi= ImageIO.read(img); //Reads in the image
//Color you are searching for
int color= 0xFF00FF00; //Green in this example
for (int x=0;x<width;x++)
for (int y=0;y<height;y++)
if(bi.getRGB(x,y)==color)
list.add(new Point(x,y));
Try using a PixelGrabber. It accepts an Image or ImageProducer.
Here's an example adapted from the documentation:
public void handleSinglePixel(int x, int y, int pixel) {
int alpha = (pixel >> 24) & 0xff;
int red = (pixel >> 16) & 0xff;
int green = (pixel >> 8) & 0xff;
int blue = (pixel ) & 0xff;
// Deal with the pixel as necessary...
}
public void handlePixels(Image img, int x, int y, int w, int h) {
int[] pixels = new int[w * h];
PixelGrabber pg = new PixelGrabber(img, x, y, w, h, pixels, 0, w);
try {
pg.grabPixels();
} catch (InterruptedException e) {
System.err.println("interrupted waiting for pixels!");
return;
}
if ((pg.getStatus() & ImageObserver.ABORT) != 0) {
System.err.println("image fetch aborted or errored");
return;
}
for (int j = 0; j < h; j++) {
for (int i = 0; i < w; i++) {
handleSinglePixel(x+i, y+j, pixels[j * w + i]);
}
}
}
In your case, you would have:
public void handleSinglePixel(int x, int y, int pixel) {
int target = 0xFFABCDEF; // or whatever
if (pixel == target) {
myArrayList.add(new java.awt.Point(x, y));
}
}

Categories