How to overlap the white pixels from binary onto original image?
Question:
I have an aerial image:
I was able to get a binary image of the riverbed of the river part:
After applying a distance transform and some segmentation techniques I was able to get a binary image of the mean riverline:
My question is: how to overlay the white pixels from the riverline so that they’re on "top" of the original image?
HereĀ“s an example:
Answers:
This is a very simple way to solve your problem. But it works.
import cv2
original = cv2.imread('original.png') # Orignal image
mask = cv2.imread('line.png') # binary mask image
result = original.copy()
for i in range(original.shape[0]):
for j in range(original.shape[1]):
result[i, j] = [255, 255, 255] if mask[i, j][0] == 255 else result[i, j]
cv2.imwrite('result.png', result) # saves modified image to result.png
Result
Let’s assume your images are numpy arrays called img
and mask
. Let’s also assume that img
has shape (M, N, 3)
, while mask
has shape (M, N)
. Finally, let’s assume that img
is off dtype np.uint8
while mask
is of type np.bool_
. If the last assumption isn’t true, start with
mask = mask.astype(bool)
Now you can set your river channel to 255 directly:
img[mask, :] = 255
If img
were a single grayscale image without a third dimension, as in your last example, you would just remove the :
from the index expression above. In fact, you could write it to work for any number of dimensions with
img[mask, ...] = 255
I have an aerial image:
I was able to get a binary image of the riverbed of the river part:
After applying a distance transform and some segmentation techniques I was able to get a binary image of the mean riverline:
My question is: how to overlay the white pixels from the riverline so that they’re on "top" of the original image?
HereĀ“s an example:
This is a very simple way to solve your problem. But it works.
import cv2
original = cv2.imread('original.png') # Orignal image
mask = cv2.imread('line.png') # binary mask image
result = original.copy()
for i in range(original.shape[0]):
for j in range(original.shape[1]):
result[i, j] = [255, 255, 255] if mask[i, j][0] == 255 else result[i, j]
cv2.imwrite('result.png', result) # saves modified image to result.png
Result
Let’s assume your images are numpy arrays called img
and mask
. Let’s also assume that img
has shape (M, N, 3)
, while mask
has shape (M, N)
. Finally, let’s assume that img
is off dtype np.uint8
while mask
is of type np.bool_
. If the last assumption isn’t true, start with
mask = mask.astype(bool)
Now you can set your river channel to 255 directly:
img[mask, :] = 255
If img
were a single grayscale image without a third dimension, as in your last example, you would just remove the :
from the index expression above. In fact, you could write it to work for any number of dimensions with
img[mask, ...] = 255