将C 拷贝托转换为Python

Converting c++ copyTo to python

本文关键字:Python 转换 拷贝      更新时间:2023-10-16

我正在尝试将以下OpenCV C 转换为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);

我不确定如何处理将step3转换为python。我在python中完成了步骤1和2,

#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)

cv::Mat::copyTo在您的情况下,简单地制作了图像的副本。实际上,您如何使用它等于使用cv::Mat::clone,因为您没有指定掩码。因此,在Python中,使用numpy.copy方法,因为OpenCV使用Numpy数组作为主要数据类型:

# Step #3
smooth = vertical.copy()

对于步骤#5,您现在正在基于蒙版复制。我已经回答了如何在我的上一篇文章中做到这一点:相当于python opencv绑定中的copyto?您正在查看第二种情况,即您要复制的矩阵已经被分配,并且只想复制掩模中非零的值。但是,为了完整的目的,我将其放在这里。

您本质上想使用smooth修改vertical,但仅在edges中的非零元素定义的smooth元素上复制。您可以使用numpy.where查找非零行和列位置,并使用它们在smoothvertical之间的正确值上复制。看起来您有灰度图像,因此这使它变得更加简单:

# Step #5
(rows, cols) = np.where(edges != 0)
vertical[rows, cols] = smooth[rows, cols]