I am developing an image segmentation application that will use watersheds. For that, I found a code that I will need to use in python. However, I\'m having a hard time conv
//Load the image
srcOriginal = Imgcodecs.imread(currentPhotoPath)
//Create a blank image of zeros (same dimension as img)
//It should be grayscale (1 color channel)
markers = Mat.zeros(srcOriginal.rows(), srcOriginal.cols(), CvType.CV_32S)
//This step is manual. The goal is to find the points
//which create the result we want. I suggest using a
//tool to get the pixel coordinates.
//Dictate the background and set the markers to 1
for (value in 0..my_canvas.pointsToDrawY.size - 1) {
markers.put(
my_canvas.pointsToDrawX[value].toInt(),
my_canvas.pointsToDrawY[value].toInt(),
1.0
)
}
//Dictate the area of interest
//I used different values for each part of the car (for visibility)
for (value in 0..my_canvas.pointsToDrawYStepTwo.size - 1) {
markers.put(
my_canvas.pointsToDrawXStepTwo[value].toInt(),
my_canvas.pointsToDrawYStepTwo[value].toInt(),
255.0
)
}
//Now we have set the markers, we use the watershed
//algorithm to generate a marked image
watershed(srcOriginal, markers)
//Plot this one. If it does what we want, proceed;
//otherwise edit your markers and repeat
val mPath1 = Environment.getExternalStorageDirectory().toString() + "/watershed.png"
Imgcodecs.imwrite(mPath1,markers)
//Make the background black, and what we want to keep white
for (x in 0 until srcOriginal.rows()-1) {
for (y in 0 until srcOriginal.cols()-1) {
if(markers.get(x,y).get(0).equals(1.0)){
markers.put(
x,
y,
0.0
)
}
if((markers[x, y].get(0) == 255.0)){
markers.put(
x,
y,
255.0
)
}
}
}
//Use a kernel to dilate the image, to not lose any detail on the outline
//I used a kernel of 3x3 pixels
val marker_tempo = Mat()
val dilatation = Mat()
markers.convertTo(marker_tempo, CvType.CV_8U)
val kernel = Mat(3, 3, CvType.CV_8U)
Imgproc.dilate(marker_tempo, dilatation, kernel)
//Plot again to check whether the dilation is according to our needs
//If not, repeat by using a smaller/bigger kernel, or more/less iterations
val mPath2 = Environment.getExternalStorageDirectory().toString() + "/dilatation.png"
Imgcodecs.imwrite(mPath2,dilatation)
//Now apply the mask we created on the initial image
val final = Mat()
Core.bitwise_and(srcOriginal, srcOriginal, final, dilatation)
//Plot the final result
val mPath = Environment.getExternalStorageDirectory().toString() + "/final.png"
Imgcodecs.imwrite(mPath,final)
numpy.zeros_like basically creates an array the same shape as the input with all zeros in it.
https://numpy.org/doc/stable/reference/generated/numpy.zeros_like.html
In this case, you have a simple 2d array so you could roll your own just by indexing through the whole array (all dimensions) and setting everything to zero.
var marker = Array(srcOriginal.rows()) {Array(srcOriginal.cols()) {0} }