Home > Software engineering >  deleting the common parts of two images
deleting the common parts of two images

Time:10-30

Say I have the following two images:

before.png:

enter image description here

after.png:

enter image description here

I'd like to remove all the parts of after.png that are in before.png so that, unto the end, I have this:

enter image description here

. My question is... how can I do this?

Here's what I've tried so far:

import cv2

refFilename = 'before.png'
newFilename = 'after.png'
outFilename = 'output.png'

imRef = cv2.imread(refFilename, cv2.IMREAD_GRAYSCALE)
th, imBW = cv2.threshold(imRef, 128, 192, cv2.THRESH_OTSU)

imNew = cv2.imread(newFilename, cv2.IMREAD_GRAYSCALE)

result = cv2.bitwise_and(imNew, imNew, imBW)

cv2.imwrite(outFilename, result)

The output, however, looks just like after.png. I also tried passing cv2.bitwise_not(imBW) to cv2.bitwise_and instead of imBW but that made no difference.

Any ideas?

CodePudding user response:

Here is one way to do that in Python/OpenCV.

  • Read the two images as grayscale
  • Convert to binary by Otsu thresholding
  • Invert the two binary images
  • Get the absolute difference
  • Invert the difference
  • Save results

Input:

enter image description here

enter image description here

import cv2

# read the two images
img1 = cv2.imread('circle1.jpg', cv2.IMREAD_GRAYSCALE)
img2 = cv2.imread('circle2.jpg', cv2.IMREAD_GRAYSCALE)

# convert to binary
bin1 = cv2.threshold(img1, 0, 255, cv2.THRESH_BINARY cv2.THRESH_OTSU)[1]
bin2 = cv2.threshold(img2, 0, 255, cv2.THRESH_BINARY cv2.THRESH_OTSU)[1]

# invert each
bin1 = 255 - bin1
bin2 = 255 - bin2

# get absdiff
diff = cv2.absdiff(bin2, bin1)

# invert
diff = 255 - diff

# save result
cv2.imwrite('circles_diff.jpg', diff)

# show result
cv2.imshow('diff',diff)
cv2.waitKey(0)

Resulting difference:

enter image description here

ADDITION

To answer your question in your comment, change cv2.absdiff to cv2.subtract.

Image:

enter image description here

enter image description here

import cv2

# read the two images
img1 = cv2.imread('circle3.jpg', cv2.IMREAD_GRAYSCALE)
img2 = cv2.imread('circle2.jpg', cv2.IMREAD_GRAYSCALE)

# convert to binary
bin1 = cv2.threshold(img1, 0, 255, cv2.THRESH_BINARY cv2.THRESH_OTSU)[1]
bin2 = cv2.threshold(img2, 0, 255, cv2.THRESH_BINARY cv2.THRESH_OTSU)[1]

# invert each
bin1 = 255 - bin1
bin2 = 255 - bin2

# get absdiff
diff = cv2.subtract(bin2, bin1)

# invert
diff = 255 - diff

# save result
cv2.imwrite('circles_diff2[![enter image description here][6]][6].jpg', diff)

# show result
cv2.imshow('diff',diff)
cv2.waitKey(0)

Result:

enter image description here

  • Related