Search code examples
opencvimage-processingmatrixcolorspixel

Efficiently tell if one image is entirely comprised of the pixel values of another in OpenCV


I am trying to find an efficient way to see if one image is a subset of another (meaning that each unique pixel in one image is also found in the other.) The repetition or ordering of the pixels do not matter.

I am working in Java, so I would like all of my operations to be completed in OpenCV for efficiency's sake.

My first idea was to export a list of unique pixel values, and compare it to the list from the second image. As there is not a built in function to extract unique pixels, I abandoned this approach.

I also understand that I can find the locations of a particular color with the inclusive inRange, and findNonZero operations.

  Core.inRange(image, color, color, tempMat); // inclusive
  Core.findNonZero(tempMat, colorLocations);

Unfortunately, this does not provide an adequate answer, as it would need to be executed per color, and would still require extracting unique pixels.

Essentially, I'm asking if there is a clever way to use the built in OpenCV functions to see if an image is comprised of the pixels found in another image.

I understand that this will not work for slight color differences. I am working on a limited dataset, and care about the exact pixel values.

To put the question more mathematically:


Solution

  • Because the only think you are interested in is the pixel values i would suggest to do the following.

    1. Compute the histogram of image 1 using hist1 = calcHist()
    2. Compute the histogram of image 2 using hist2 = calcHist()
    3. Calculate the difference vector diff = hist1 - hist2
    4. Check if each bin of the hist of the subimage is less or equal than the corresponding bin in the hist of the bigger image

    Thanks to Miki for the fix.