OpenCV-Python is an easy-to-develop environment for developing algorithms that use OpenCV. Here is a memo that will give you a hint when porting the algorithm developed there to C ++.
For OpenCV-Python: Use of numpy.array type → Replacement with cv :: Mat type numpy.array type specific method Replacement with cv :: Mat type method.
This kind of rewriting is easy. Even if you do not have enough experience to build image processing algorithms, you can rewrite OpenCV-Python code to OpenCV C ++ if you have experience with C ++.
numpy.array | cv::Mat | important point |
---|---|---|
a = np.ones((h,w), dtype=np.uint8) | cv::Mat a=cv::Mat::ones(cv::Size(w, h), cv::CV_8U); | |
shape | size | shape is[h, w, channel]Order, or[h, w] |
img.shape | cv::Size(img.rows, img.cols) | |
img = cv2.imread("lena.png "); imgRGB=img[:, :, ::-1] | cv::Mat img = cv::imread("lena.png "); | cv2.imread()Is in order of BGR |
import pylab as plt; plt.imshow(imgRGB) | cv::imshow("title", img); | matplotlib imshow()Is Matlab imshow()Close to |
a[:, :] = 0 | a.setTo(0); | For color images a[:, :, :] = 0 。setTo()Argument is a constant |
a[b>127] = 255 | a.setTo(255, b > 127); | |
a = b+0 | b.copyTo(a); | In numpy just a=If b, then a is an alias for b, and the substance is the same. |
a[c==d] = b[c==d] | b.copyTo(a, c==d); | |
a = np.array(b, dtype=np.float32)/255.0 | b.convertTo(a, CV_32F, 1.0/255); |
OpenCV-Python code example
python
# -*- coding: utf-8 -*-
import cv2
import numpy as np
img = cv2.imread("lena.png ", 0)
b = np.zeros(img.shape[:2], dtype=np.uint8)
b[img > 128] = 255
cv2.imwrite("junk.png ", b)
Rewritten C ++ source code example
python
#include <opencv2/opencv.hpp>
int main(int argc, char* argv[]) {
cv::Mat img= cv::imread("lena.png ", 0);
cv::Mat b = cv::Mat::zeros(cv::Size(img.rows, img.cols), CV_8U);
b.setTo(255, img>127);
cv::imwrite("junk_cpp.png ", b);
}
Image of execution result
Useful functions in numpy numpy.rot90(m, k=1, axes=(0, 1) (https://docs.scipy.org/doc/numpy-1.12.0/reference/generated/numpy.rot90.html)
Recommended Posts