简体   繁体   English

如何将 opencv Mat 转换为 numpy.ndarray?

[英]How to convert an opencv Mat into a numpy.ndarray?

I have a code written in java (android) that open the camera of the phone and show frames.我有一个用 java (android) 编写的代码,可以打开手机的摄像头并显示帧。 The below code represents the method in which we can retrieve frames.下面的代码代表了我们可以检索帧的方法。 The project used Chaquopy to interpret python code.该项目使用 Chaquopy 来解释 Python 代码。

 @Override
    public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {

        mRgba = inputFrame.rgba();
        Python py = Python.getInstance();

        PyObject pym = (PyObject) 
        py.getModule("MyPythonClass").callAttr("call",mRgba);

        return mRgba;
    }

The python code is used to retrieve the frame (represented by "mRgba" which is a Mat in the java code) for further treatment The problem is to find a solution to convert this Mat into a type that could be interpreted by python code : python代码用于检索frame(在java代码中用“mRgba”表示,它是一个Mat)进行进一步处理问题是找到一个解决方案,将这个Mat转换成python代码可以解释的类型:

def call(frame):

    im = imutils.resize(frame, width=min(300, frame.shape[1]))

"frame" is supposed to be the Mat retrieved by the java code and sent to the function "call" “frame”应该是由java代码检索并发送到函数“call”的Mat

I found a solution by transforming the Mat into a byteArray in the java side我通过在java端将Mat转换为byteArray找到了一个解决方案

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
        byteArray = byteArrayOutputStream .toByteArray();

and in the python side the byteArray retrieved is transformed into a PIL image and then to a numpy array :在 python 端,检索到的 byteArray 被转换为 PIL 图像,然后转换为 numpy 数组:

def call(imp):

    pic = Image.open(io.BytesIO(bytes(imp)))
    open_cv_image = np.array(pic)
    # Convert RGB to BGR
    frame = open_cv_image[:, :, ::-1].copy()
    im = imutils.resize(frame, width=min(300, frame.shape[1]))

Hope that could help.希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM