jashliao 用 VC++ 實現 fanfuhan OpenCV 教學003 ~ opencv-003-圖像對象(Mat)創建與賦值 [圖片拷貝(複製)、建立空白畫布、建立運算濾波器(Filter)]
jashliao 用 VC++ 實現 fanfuhan OpenCV 教學003 ~ opencv-003-圖像對象(Mat)創建與賦值 [圖片拷貝(複製)、建立空白畫布、建立運算濾波器(Filter)]
資料來源: https://fanfuhan.github.io/
https://fanfuhan.github.io/2019/03/21/opencv-003/
GITHUB:https://github.com/jash-git/fanfuhan_ML_OpenCV
https://github.com/jash-git/jashliao-implements-FANFUHAN-OPENCV-with-VC
★前言:
★主題:
OPENCV中使用『Mat型態變數』實作圖片拷貝(複製)、建立空白畫布、建立運算遮罩(mask)
★C++
// VC_FANFUHAN_OPENCV003.cpp : 定義主控台應用程式的進入點。 // #include "stdafx.h" /* // Debug | x32 通用屬性 | C/C++ | | 一般 | | 其他 Include 目錄 -> C:\opencv\build\include | | 連結器 | |一一般 | | 其他程式庫目錄 -> C:\opencv\build\x64\vc15\lib | | |一輸入 | | 其他相依性 -> opencv_world411d.lib;%(AdditionalDependencies) // Releas | x64 組態屬性 | C/C++ | | 一般 | | 其他 Include 目錄 -> C:\opencv\build\include | | 連結器 | |一般 | | 其他程式庫目錄 -> C:\opencv\build\x64\vc15\lib | | |一輸入 | | 其他相依性 -> opencv_world411.lib;%(AdditionalDependencies) */ #include <iostream> #include <opencv2/opencv.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> using namespace std; using namespace cv; void pause() { printf("Press Enter key to continue..."); fgetc(stdin); } int main() { Mat src = imread("../../images/l_hires.jpg");//IDE 測試路徑 //Mat src = imread("../../../images/l_hires.jpg");//執行檔 測試路徑 if (src.empty()) { cout << "could not load image..." << endl; pause(); return -1; } else { // 通过克隆或复制创建图像对象,m1和src指向不同内存块 Mat m1 = src.clone(); Mat m2; src.copyTo(m2); // 赋值法,m3和src指向同一内存块 Mat m3 = src; namedWindow("input"); imshow("input", m3); // 创建空白图像 Mat m4 = Mat::zeros(src.size(), src.type()); Mat m5 = Mat::zeros(Size(512, 512), CV_8UC3); Mat m6 = Mat::ones(Size(512, 512), CV_8UC3); Mat m7 = Mat(Size(512, 512), CV_8UC3,Scalar(255,255,255));//白色畫布 namedWindow("m4-input(zeros)"); imshow("m4-input(zeros)", m4); namedWindow("m5-Size(512, 512)[zeros]"); imshow("m5-Size(512, 512)[zeros]", m5); namedWindow("m6-Size(512, 512)[ones]"); imshow("m6-Size(512, 512)[ones]", m6); namedWindow("m7-Size(512, 512)[Scalar(255,255,255)]"); imshow("m7-Size(512, 512)[Scalar(255,255,255)]", m7); // kernel: [0, -1, 0 // -1, 5, -1 // 0, -1, 0] Mat kernel = (Mat_<char>(3, 3) << 0, -1, 0, -1, 5, -1, 0, -1, 0); waitKey(0); } return 0; }
★Python
import cv2 as cv import numpy as np src = cv.imread("../images/liuyifei_1.png") cv.namedWindow("input", cv.WINDOW_AUTOSIZE) cv.imshow("input", src) # 克隆图像 m1 = np.copy(src) # 赋值 m2 = src src[100:200,200:300,:] = 255 # 第三维代表图像通道 cv.imshow("m2",m2) m3 = np.zeros(src.shape, src.dtype) cv.imshow("m3", m3) m4 = np.zeros([512,512], np.uint8) # m4[:,:] =127 try to give gray value 127 cv.imshow("m4", m4) m5 = np.ones(shape=[512,512,3], dtype=np.uint8) m5[:,:,0] = 255 cv.imshow("m5", m5) cv.waitKey(0) cv.destroyAllWindows()
★結果圖:
★延伸說明/重點回顧:
OPENCV的(Mat::zeros、Mat::ones)空白畫布預設都是黑底
OPENCV使用Scalar(255,255,255)建立非黑色底(白色)畫布