无法将代码从Python转换为C#

时间:2019-08-16 00:42:46

标签: c# python numpy opencv opencvsharp

已解决:我正在检测护照的机读区。我有一个策略,但是由于缺乏文档,所以我无法转换以下代码行。我的项目使用OpenCvSharp和NumSharp,这是numpy到c#的端口。任何帮助将不胜感激。

Python代码:

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# smooth the image using a 3x3 Gaussian, then apply the blackhat
# morphological operator to find dark regions on a light background
gray = cv2.GaussianBlur(gray, (3, 3), 0)
blackhat = cv2.morphologyEx(gray, cv2.MORPH_BLACKHAT, rectKernel)

# compute the Scharr gradient of the blackhat image and scale the
# result into the range [0, 255]
gradX = cv2.Sobel(blackhat, ddepth=cv2.CV_32F, dx=1, dy=0, ksize=-1)
gradX = np.absolute(gradX)
(minVal, maxVal) = (np.min(gradX), np.max(gradX))
gradX = (255 * ((gradX - minVal) / (maxVal - minVal))).astype("uint8")

C#代码:

// smooth the image using a 3x3 Gaussian, then apply the blackhat
// morphological operator to find dark regions on a light background
smallImage = smallImage.GaussianBlur(new Size(3, 3), 0);
Cv2.MorphologyEx(smallImage, blackhat, MorphTypes.BlackHat, rectKernel);

//计算黑帽图像的Scharr梯度并缩放             //结果在[0,255]范围内             Cv2.Sobel(blackhat,gradX,MatType.CV_32F,1,0,-1,1,0);

        //(minVal, maxVal) = (np.min(gradX), np.max(gradX))
        double minVal, maxVal;
        gradX.MinMaxLoc(out minVal, out maxVal);

        //gradX = (255 * ((gradX - minVal) / (maxVal - minVal))).astype("uint8")
        gradX.ConvertTo(gradX, MatType.CV_8U, 255.0 / (maxVal - minVal), -255.0 / minVal);

具体来说,我在Python代码的最后一行遇到了麻烦。我不确定如何在c#中执行该计算。我也不确定是否正确获取了minValmaxVal值。

2 个答案:

答案 0 :(得分:0)

一个8位无符号整数是C#中的byte。您可以这样做:

var gradX = Convert.ToByte(255 * ((gradX - minVal) / (maxVal - minVal)));

我不确定这些最小和最大函数在做什么,所以我无能为力。

答案 1 :(得分:0)

这是我原来的问题的解决方案:

// compute the Scharr gradient of the blackhat image and scale the
// result into the range [0, 255]
Cv2.Sobel(blackhat, gradX, MatType.CV_32F, 1, 0, -1, 1, 0);

//(minVal, maxVal) = (np.min(gradX), np.max(gradX))
double minVal, maxVal;
gradX.MinMaxLoc(out minVal, out maxVal);

//gradX = (255 * ((gradX - minVal) / (maxVal - minVal))).astype("uint8")
gradX.ConvertTo(gradX, MatType.CV_8U, 255.0 / (maxVal - minVal), -255.0 / minVal);