Skip to content Skip to sidebar Skip to footer

How Do I Make A Mask From One Image And Then Transfer It To Another?

I'm trying to solve a homework problem where I need to get a mask from one image (DAPI) and then apply it to the second image (NPM1) of cells (they are the same cells in the exact

Solution 1:

I limited my solution to the use of OpenCV, numpy, and matplotlib.

The general approach is the following:

  1. Load both images as grayscale images, see cv2.imread.
  2. Create a binary mask from the DAPI image using binary thresholding at intensity value 25, see cv2.threshold.
  3. Do some morphological opening to get rid of possible small artifacts, see cv2.morphologyEx and cv2.getStructuringElement.
  4. Calculate the histogram of the NPM1 image, only incorporating the masked pixels, see cv2.calcHist.

Here's the complete code:

import cv2
import matplotlib.pyplot as plt
import numpy as np

# Load images as grayscale
dapi = cv2.imread('images/NOTREATDAPI.jpg', cv2.IMREAD_GRAYSCALE)
npm1 = cv2.imread('images/NOTREATNPM1.jpg', cv2.IMREAD_GRAYSCALE)

# Create a mask using the DAPI image and binary thresholding at 25
_, mask = cv2.threshold(dapi, 25, 255, cv2.THRESH_BINARY)

# Do some morphological opening to get rid of small artifacts
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (15, 15)))

# Calculate the histogram using the NPM1 image and the obtained binary mask
hist = cv2.calcHist([npm1], [0], mask, [256], [0, 256])

# Show bar plot of calculated histogram
plt.bar(np.arange(256), np.squeeze(hist))
plt.show()

# Show mask image
cv2.imshow('Mask', mask)
cv2.waitKey(0)
cv2.destroyAllWindows()

The mask then looks like this:

Mask

And, the histogram might look like this:

Histogram

Hope that helps!

P.S. Next time, better use the opencv and python tags instead of only using the cv2 tag. You'll reach way more people.


Post a Comment for "How Do I Make A Mask From One Image And Then Transfer It To Another?"