如何将opencv Mat转换为numpy.ndarray? [英] How to convert an opencv Mat into a numpy.ndarray?

查看:2156
本文介绍了如何将opencv Mat转换为numpy.ndarray?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用Java(android)编写的代码,可以打开手机的摄像头并显示框架.以下代码代表了我们可以检索帧的方法.该项目使用Chaquopy解释python代码.

I have a code written in java (android) that open the camera of the phone and show frames. The below code represents the method in which we can retrieve frames. The project used Chaquopy to interpret python code.

 @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;
    }

python代码用于检索框架(由"mRgba"表示,它是java代码中的Mat),以作进一步处理 问题是找到一种解决方案,将该Mat转换为可由python代码解释的类型:

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 :

def call(frame):

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

帧"应该是由Java代码检索并发送到函数调用"的Mat.

"frame" is supposed to be the Mat retrieved by the java code and sent to the function "call"

推荐答案

我找到了一种解决方案,方法是将Mat转换为Java端的byteArray

I found a solution by transforming the Mat into a byteArray in the java side

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

并且在python端,将检索到的byteArray转换为PIL图像,然后转换为numpy数组:

and in the python side the byteArray retrieved is transformed into a PIL image and then to a numpy array :

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

希望有帮助.

这篇关于如何将opencv Mat转换为numpy.ndarray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆