Skip to content

Instantly share code, notes, and snippets.

@garybradski
Created September 21, 2017 00:16
Show Gist options
  • Save garybradski/4659bf8dc8a569f29bbc5da379e43b15 to your computer and use it in GitHub Desktop.
Save garybradski/4659bf8dc8a569f29bbc5da379e43b15 to your computer and use it in GitHub Desktop.
Python: Methods of copying a mask indicated region of one image into another
#Method 1, pythonic
img_res = np.zeros(image.shape, np.uint8) #create the image
img_res[:, :] = (0, 0, 200) #color it red
idx = (mask != 0)
img_res[idx] = image[idx]
#Method 2 OpenCV
img_red = np.zeros(image.shape, np.uint8) #create the image
img_red[:, :] = (0, 0, 200) #color it red
fg = cv2.bitwise_and(image, image, mask=mask) #isolate the segmented region
bg = cv2.bitwise_and(img_red, img_red, mask=(255 - mask)) #create the inverse segmented image
img_res = fg + bg #combine
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment