1

I am trying to convert the following OpenCV C++ to Python:

Cpp:

//step1
Mat edges;
adaptiveThreshold(vertical, edges, 255, CV_ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 3, -2);
imshow("edges", edges);
// Step 2
Mat kernel = Mat::ones(2, 2, CV_8UC1);
dilate(edges, edges, kernel);
imshow("dilate", edges);
// Step 3
Mat smooth;
vertical.copyTo(smooth);
// Step 4
blur(smooth, smooth, Size(2, 2));
// Step 5
smooth.copyTo(vertical, edges);
// Show final result
imshow("smooth", vertical);

I'm not sure how to handle converting step3 to python. I have done step1 and 2 as below in python

#step1
edges = cv2.adaptiveThreshold(vertical,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,3,-2)

#step2 
kernel = np.ones((2, 2), dtype = "uint8")
dilated = cv2.dilate(edges, kernel)
rayryeng
  • 102,964
  • 22
  • 184
  • 193
Anthony
  • 33,838
  • 42
  • 169
  • 278

1 Answers1

2

cv::Mat::copyTo in your case simply makes a copy of the image. In fact, how you're using it is equivalent to using cv::Mat::clone as you aren't specifying a mask. As such in Python, use the numpy.copy method as OpenCV uses NumPy arrays as the main datatype:

# Step #3
smooth = vertical.copy()

For Step #5, you are now copying based on a mask. I've already answered how to do that in a previous post of mine: Equivalent of copyTo in Python OpenCV bindings?. You are looking at the second situation where the matrix you are copying to has already been allocated and only want to copy over the values that are non-zero in the mask. However, for the sake of completeness I'll put it here for you.

You essentially want to modify vertical using smooth but only copying over the elements of smooth that are defined by the non-zero elements in edges. You can use numpy.where to find the non-zero row and column locations and use these to copy over the right values between smooth and vertical. It also looks like you have a grayscale image so this makes it even simpler:

# Step #5
(rows, cols) = np.where(edges != 0)
vertical[rows, cols] = smooth[rows, cols]
Community
  • 1
  • 1
rayryeng
  • 102,964
  • 22
  • 184
  • 193
  • 1
    Thank you! this makes sense now. Also, what you've explained for step 5 is immensely helpful. In a larger context, I'm trying to convert a c++ code into python. I've done it but I suspect it is incorrect because the results aren't the same. I've posted a separate question that I would really appreciate your input on http://stackoverflow.com/questions/42453892/converting-c-opencv-to-python – Anthony Feb 25 '17 at 08:49
  • You are most welcome. I do have to sleep now but I will examine your question when I wake up. – rayryeng Feb 25 '17 at 08:52