【笔记】opencv的python使用 腐蚀模糊背景分割等处理图像
概括
從概念上講,一個字節能表示0到255的整數。目前,對于所有的實時圖像應用而言, 雖然有其他的表示形式,但一個像素通常由每個通道的一個字節表示。
一個OpenCV圖像是.array類型的二維或三維數組。8位的灰度圖像是一個含有字節值 的二維數組。一個24位的BGR圖像是一個三維數組,它也包含了字節值。可使用表達式 訪問這些值,例如image[0,0]或image[0, 0, 0]。第一個值代表像素的y坐標或行,0表示 頂部;第二個值是像素的x坐標或列,0表示最左邊;第三個值(如果可用的話)表示顏色 通道。
C++接口:
1。處理圖片
效果:(原圖就不發了
application_trace.cpp
background segmentation(來自官方示例
#include "opencv2/core.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/video.hpp" #include "opencv2/videoio.hpp" #include "opencv2/highgui.hpp" #include <iostream>using namespace std; using namespace cv;int main(int argc, const char** argv) {const String keys = "{c camera | 0 | use video stream from camera (device index starting from 0) }""{fn file_name | | use video file as input }""{m method | mog2 | method: background subtraction algorithm ('knn', 'mog2')}""{h help | | show help message}";CommandLineParser parser(argc, argv, keys);parser.about("This sample demonstrates background segmentation.");if (parser.has("help")){parser.printMessage();return 0;}int camera = parser.get<int>("camera");String file = parser.get<String>("file_name");String method = parser.get<String>("method");if (!parser.check()){parser.printErrors();return 1;}VideoCapture cap;if (file.empty())cap.open(camera);else{file = samples::findFileOrKeep(file); // ignore gstreamer pipelinescap.open(file.c_str());}if (!cap.isOpened()){cout << "Can not open video stream: '" << (file.empty() ? "<camera>" : file) << "'" << endl;return 2;}Ptr<BackgroundSubtractor> model;if (method == "knn")model = createBackgroundSubtractorKNN();else if (method == "mog2")model = createBackgroundSubtractorMOG2();if (!model){cout << "Can not create background model using provided method: '" << method << "'" << endl;return 3;}cout << "Press <space> to toggle background model update" << endl;cout << "Press 's' to toggle foreground mask smoothing" << endl;cout << "Press ESC or 'q' to exit" << endl;bool doUpdateModel = true;bool doSmoothMask = false;Mat inputFrame, frame, foregroundMask, foreground, background;for (;;){// prepare input framecap >> inputFrame;if (inputFrame.empty()){cout << "Finished reading: empty frame" << endl;break;}const Size scaledSize(640, 640 * inputFrame.rows / inputFrame.cols);resize(inputFrame, frame, scaledSize, 0, 0, INTER_LINEAR);// pass the frame to background modelmodel->apply(frame, foregroundMask, doUpdateModel ? -1 : 0);// show processed frameimshow("image", frame);// show foreground image and mask (with optional smoothing)if (doSmoothMask){GaussianBlur(foregroundMask, foregroundMask, Size(11, 11), 3.5, 3.5);threshold(foregroundMask, foregroundMask, 10, 255, THRESH_BINARY);}if (foreground.empty())foreground.create(scaledSize, frame.type());foreground = Scalar::all(0);frame.copyTo(foreground, foregroundMask);imshow("foreground mask", foregroundMask);imshow("foreground image", foreground);// show background imagemodel->getBackgroundImage(background);if (!background.empty())imshow("mean background image", background );// interact with userconst char key = (char)waitKey(30);if (key == 27 || key == 'q') // ESC{cout << "Exit requested" << endl;break;}else if (key == ' '){doUpdateModel = !doUpdateModel;cout << "Toggle background update: " << (doUpdateModel ? "ON" : "OFF") << endl;}else if (key == 's'){doSmoothMask = !doSmoothMask;cout << "Toggle foreground mask smoothing: " << (doSmoothMask ? "ON" : "OFF") << endl;}}return 0;}效果:
3。腐蝕
#include "opencv2/core.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/video.hpp" #include "opencv2/videoio.hpp" #include "opencv2/highgui.hpp" #include"opencv2/imgproc/imgproc.hpp" #include <iostream>using namespace std; using namespace cv;int main() {Mat img = imread("/home/heziyi/圖片/7.jpg");imshow("old",img);Mat element = getStructuringElement(MORPH_RECT,Size(15,15));Mat dimg;erode(img,dimg,element);imshow("new",dimg);waitKey(0); }4。模糊:
int main() {Mat img = imread("/home/heziyi/圖片/6.jpg");imshow("old",img);Mat element = getStructuringElement(MORPH_RECT,Size(15,15));Mat dimg;blur(img,dimg,Size(1,1));imshow("new",dimg);waitKey(0); }5。邊緣檢測:
#include "opencv2/core.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/video.hpp" #include "opencv2/videoio.hpp" #include "opencv2/highgui.hpp" #include"opencv2/imgproc/imgproc.hpp" #include <iostream>using namespace std; using namespace cv;int main() {Mat img = imread("/home/heziyi/圖片/6.jpg");imshow("old",img);Mat element = getStructuringElement(MORPH_RECT,Size(15,15));Mat dimg,edge,grayimg;dimg.create(img.size(),img.type());cvtColor(img,grayimg,COLOR_BGRA2GRAY);blur(grayimg,edge,Size(3,3));Canny(edge,edge,3,9,3);imshow("new",edge);waitKey(0); }VideoCapture 提供了攝像機或視頻文件捕獲視頻的C++接口,作用是從視頻文件或攝像頭捕獲視頻并顯示出來。
//循環顯示每一幀 while(1) { Mat frame;//用于存儲每一幀圖像 capture>>frame; imshow("picture",frame) waitKey(30);//延時30毫秒 }python接口:
使用numpy.array訪問圖像數據
將BGR圖像在(0,0)處的像素轉化為白 像素。
img[0,0] = [255, 255, 255]通過三元數組的索引將像素的顏色值設為0
下面的代碼可將圖像所有的G (綠色)值設為0:
并將第一個區域的值分配給第二個區域(將圖 像的一部分拷貝到該圖像的另一個位置):
img[y,220]=[z,210,56]my_roi = img[0:200 , 0:200]img[300:500, 300:500] = my_roicv2.imshow('ppp',img)cv2.waitKey(30000)結果:
視頻文件的讀寫
OpenCV提供了 VideoCapture類和VideoWriter類來支持各種格式的視頻文件。支持 的格式類型會因系統的不同而變化,但應該都支持AVI格式。在到達視頻文件末尾之前, VideoCapture類可通過read()函數來獲取新的幀,每幀是一幅基于BGR格式的圖像。
可將一幅圖像傳遞給VideoWriter類的write()函數,該函數會將這幅圖像加到 VideoWriter類所指向的文件中。下面給出了一個示例,該示例讀取AVI文件的幀,并采用 YUV顏色編碼將其寫入另一個幀中:
總結
以上是生活随笔為你收集整理的【笔记】opencv的python使用 腐蚀模糊背景分割等处理图像的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在pycharm中升级pip失败和pip
- 下一篇: websocket python爬虫_p