简体   繁体   中英

How to subtract two images using python opencv2 to get the foreground object

Is there any way to subtract two images in python opencv2 ?

  • Image 1 : Any image (eg. a house Image) (static image)
  • Image 2 : The same Image with an Object (In house, a person is standing...) (static image + dynamic objects)
  • Image 3 = Image 2 - Image 1

If we subtract Image2 from Image1 means Image3 should give Object(person) only.

Try background subtraction .

Use cv2.subtract(img1,img2) instead of arithmetic operation, as cv2 will take care of negative values.

If the background in the two images are exactly the same, you can subtract them as you mention in your post.

image1 = imread("/path/to/image1")
image2 = imread("/path/to/image2")
image3 = image1 - image2

@dvigneshwr's answer does a subtraction where the resulting negative values are rounded up to 0. @Taha Anwar M-Holmes' answer preserves the negatives but changes the datatype of the resulting array so its no longer a conventional image type.

For those wanting to identify a foreground from a background image based on the absolute difference in values and return an array of the same data type as the inputs (that's how I ended up here), use absdiff .

Assuming the arrays are the same width and height...

import cv2 as cv

image3 = cv.absdiff(image1, image2)

Its worth noting that the OP did not provide any details wrt to the images being subtracted here... depending on what the contents of the images are, all of these approaches may answer the OP's question.

cv2.subtract does not work it just binds the values between 0-255 so if you wanna get negative values just convert the image from unit8 to int32 or int64. Note unint8 could only take on the values of 0-255 thus it could not handle negative values

image1= np.int32(image1)

image2= np.int32(image2)

image3 = image1 - image2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM