python
# -*- coding: utf-8 -*-
import cv2 as cv
import numpy as np
def function():
img = cv.imread("./image.jpg")
cv.namedWindow("input", cv.WINDOW_AUTOSIZE)
cv.imshow("input", img)
gray_img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cv.namedWindow("gray_image", cv.WINDOW_AUTOSIZE)
cv.imshow("gray_image", gray_img)
img1 = np.copy(img)
img2 = img
#虽然是在赋值后才做的修改,但是还是会影响img2
img[100: 200, 200: 300, :] = 0
cv.imshow("fuzhi", img2)
cv.imshow("xiugaixiangsu", img)
img3 = np.zeros(img.shape, img.dtype)
cv.imshow("np.zeros", img3)
img4 = np.ones(shape = [512, 512, 3], dtype = np.uint8)
img4[:, :, 0] = 255
cv.imshow("np.ones, B_channel=255", img4)
img5 = np.zeros([512, 512], np.uint8)
cv.imshow("erweishape", img5)
function()
cv.waitKey(0)
cv.destroyAllWindows()
c++
和Python中使用numpy作为图片的容器不同,c++中目前使用Mat类型作为image的容器(OpenCV2.x之前为IplImage,它需要程序员自己管理内存),Mat类型的结构为:一个表示图片信息的矩阵头和一个指向存储图片数据的矩阵的指针。基于这个结构c++中给新Mat值时,赋值操作(=)和拷贝构造函数(Mat img1(img))仅仅复制矩阵头,而新旧Mat指向同一个图片矩阵,所以这种方式比较节省时间;而clone()和copyTo()需要复制矩阵头和图片矩阵,所以比较费时间
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main() {
Mat img = imread("E:\\varietyShop\\bjut\\study\\knowledgePlanet\\image.jpg");
imshow("input", img);
//克隆
Mat img_copy = img.clone();
//赋值
Mat img_give = img;
//复制
Mat img_copyto;
img.copyTo(img_copyto);
imshow("copy", img_copyto);
//拷贝构造函数
Mat img4(img);
Mat img1 = Mat::zeros(img.size(), img.type());
Mat img2 = Mat::zeros(Size(512, 512), CV_8UC3);
Mat img3 = Mat::ones(Size(512, 512), CV_8UC3);
Mat kernal = (Mat_<char>(3, 3) << 0, -1, 0, -1, 5, -1, 0, -1, 0);
waitKey(0);
return 0;
}
网友评论