在Python中使用OpenCV创建Mat

6
我习惯于Java对OpenCV的实现。我想创建一个Mat结构,填充数据,提取一个submat,然后应用一些图像变换。在Java中,我使用以下代码:
my_mat = new Mat(my_rows, my_cols, CvType.CV_8U);
my_mat.put(0, 0, my_data);
my_mat.submat(0, my_other_rows, 0, my_other_cols);

但我没有在Python的OpenCV中找到任何有效的东西。我在OpenCV论坛上找到了这个链接:cv2.CreateMat in python,但是链接已经失效。

2个回答

4
尽管这个问题很久以前就被问过了,但这应该会帮助到今天寻找答案的人。
这适用于 opencv 版本 >= 2.X。在 Python 中,opencv 图像现在表示为 numpy 数组。因此,可以按照以下方式简单地创建一个 Mat 对象:
cvImg = np.zeros((rows, columns, channels), dtype = "uint8")

1
它是行,然后列。 - Christoph Rackwitz

1

对于 OpenCV 1.x 版本:

您可以使用 CreateMat 来完成此操作:

创建矩阵头并分配矩阵数据。

Python: cv.CreateMat(rows, cols, type) → mat
    Parameters: 
        rows – Number of rows in the matrix
        cols – Number of columns in the matrix
        type – The type of the matrix elements in the form CV_<bit depth><S|U|F>C<number of channels> , where S=signed, U=unsigned, F=float. For example, CV _ 8UC1 means the elements are 8-bit unsigned and the there is 1 channel, and CV _ 32SC2 means the elements are 32-bit signed and there are 2 channels.

该函数调用等同于以下代码:
CvMat* mat = cvCreateMatHeader(rows, cols, type);
cvCreateData(mat);

对于cv2界面:

Python的新cv2界面将numpy数组集成到OpenCV框架中,这使得操作更加简单,因为它们用简单的多维数组表示。 以下是一个起始示例:

import numpy as np, cv
vis = np.zeros((384, 836), np.float32)
h,w = vis.shape
vis2 = cv.CreateMat(h, w, cv.CV_32FC3)
vis0 = cv.fromarray(vis)

2
谢谢,问题在于我得到了AttributeError: 'module' object has no attribute 'CreateMat'... - epsilones
你使用的是哪个版本的cv/cv2? - Vtik
我正在使用 OpenCV 3.0 - epsilones
看起来你已经在做这个了。 - Vtik
2
它不起作用。你能否改进你的答案? - Cătălina Sîrbu
3
这个答案已经过时了,甚至没有使用现代的OpenCV API。请忽略它。 - Christoph Rackwitz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接