日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

【笔记】opencv的python使用 腐蚀模糊背景分割等处理图像

發布時間:2024/9/30 python 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【笔记】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

#include <iostream>#include <opencv2/core.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/highgui.hpp> #include <opencv2/videoio.hpp> #include <opencv2/core/utils/trace.hpp>using namespace cv; using namespace std;static void process_frame(const cv::UMat& frame) {CV_TRACE_FUNCTION(); // OpenCV Trace macro for functionimshow("Live", frame);UMat gray, processed;cv::cvtColor(frame, gray, COLOR_BGR2GRAY);Canny(gray, processed, 32, 64, 3);imshow("Processed", processed); } int main(int argc, char** argv) {CV_TRACE_FUNCTION();cv::CommandLineParser parser(argc, argv,"{help h ? | | help message}""{n | 100 | number of frames to process }""{@video | 0 | video filename or cameraID }");if (parser.has("help")){parser.printMessage();return 0;}VideoCapture capture;std::string video = parser.get<string>("@video");if (video.size() == 1 && isdigit(video[0]))capture.open(parser.get<int>("@video"));elsecapture.open(samples::findFileOrKeep(video)); // keep GStreamer pipelinesint nframes = 0;if (capture.isOpened()){nframes = (int)capture.get(CAP_PROP_FRAME_COUNT);cout << "Video " << video <<": width=" << capture.get(CAP_PROP_FRAME_WIDTH) <<", height=" << capture.get(CAP_PROP_FRAME_HEIGHT) <<", nframes=" << nframes << endl;}else{cout << "Could not initialize video capturing...\n";return -1;}int N = parser.get<int>("n");if (nframes > 0 && N > nframes)N = nframes;cout << "Start processing..." << endl<< "Press ESC key to terminate" << endl;UMat frame;for (int i = 0; N > 0 ? (i < N) : true; i++){CV_TRACE_REGION("FRAME"); // OpenCV Trace macro for named "scope" region{CV_TRACE_REGION("read");capture.read(frame);if (frame.empty()){cerr << "Can't capture frame: " << i << std::endl;break;}// OpenCV Trace macro for NEXT named region in the same C++ scope// Previous "read" region will be marked complete on this line.// Use this to eliminate unnecessary curly braces.CV_TRACE_REGION_NEXT("process");process_frame(frame);CV_TRACE_REGION_NEXT("delay");if (waitKey(1) == 27/*ESC*/)break;}}return 0;}

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[:,:,1]=0cv2.imshow('ppp',img)cv2.waitKey(30000)

并將第一個區域的值分配給第二個區域(將圖 像的一部分拷貝到該圖像的另一個位置):

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顏色編碼將其寫入另一個幀中:

import cv2 videoCapture = cv2.VideoCapture(1 MyInputVid.avi1) fps = videoCapture.get(cv2.CAP_PROP_FPS) size = (int(videoCapture.get(cv2.CAP_PROP_FRAME_WIDTH)), int(videoCapture.get(cv2.CAP_PROP_FRAME_HEIGHT))) videoWriter = cv2.VideoWriter( 'MyOutputVid.avi', cv2.VideoWriter_fourcc('I','4','2','0'),fps,size) success, frame = videoCapture.read() while success: # Loop until there are no more frames. videoWriter.write(frame) success, frame = videoCapture.read()

總結

以上是生活随笔為你收集整理的【笔记】opencv的python使用 腐蚀模糊背景分割等处理图像的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。