我想将这两行代码从C ++转换为Python。我在使用convertTo()时遇到了麻烦。
C ++:
filter2D(src, imgLaplacian, CV_32F, kernel);
imgLaplacian.convertTo(imgLaplacian, CV_8UC3);
Python :(我试过这个)
imgLaplacian = cv2.filter2D(src, cv2.CV_32F, kernel)
imgLaplacian = cv2.convertScaleAbs(imgLaplacian)
虽然两者都得到了uint8类型和3个通道的图像(我使用dtype和shape检查过),但当我显示生成的图像时,它看起来不同。在Python中还有另一种从float32到8UC3的方法吗?
使用this image。完整代码以便更好地理解:
C ++:
#include <opencv2/opencv.hpp>
using namespace cv;
int main(int, char** argv)
{
Mat src = imread(argv[1]);
if (!src.data)
return -1;
Mat kernel = (Mat_<float>(3,3) <<
1, 1, 1,
1, -8, 1,
1, 1, 1);
Mat imgLaplacian;
Mat sharp = src;
filter2D(sharp, imgLaplacian, CV_32F, kernel);
imgLaplacian.convertTo(imgLaplacian, CV_8UC3);
imshow( "Laplace Filtered Image", imgLaplacian );
waitKey(0);
return 0;
}
的Python:
import sys
import cv2
import numpy as np
def main(argv):
src = cv2.imread(sys.argv[1], cv2.IMREAD_COLOR)
if src is None:
return -1
kernel = np.array((
[1, 1, 1],
[1, -8, 1],
[1, 1, 1]), dtype="float32")
sharp = src
imgLaplacian = cv2.filter2D(sharp, cv2.CV_32F, kernel)
imgLaplacian = cv2.convertScaleAbs(imgLaplacian)
cv2.imshow('Laplace Filtered Image', imgLaplacian)
cv2.waitKey(0)
return 0
if __name__ == "__main__":
main(sys.argv[1:])
C ++中的结果图像:
Python中的结果图像:(看起来更模糊)