cv2 基础操作技巧

修改图片某一通道的值

输入:

import cv2
import numpy as np
img = cv2.imread('RandomGray.png')
img[:,:,0] = 255

cv2.imshow('RRR.png',img)
cv2.waitKey()

输出:

cv2 基础操作技巧_第1张图片

将图像某块区域拷贝到另一块区域

import cv2
import numpy as np
img = cv2.imread('1.png')
img[:,:,0] = 255
my_roi = img[0:100,0:100]
img[100:200,100:200] = my_roi

cv2.imshow('RRR.png',img)
cv2.waitKey()

输出:

cv2 基础操作技巧_第2张图片

视频文件的读写操作:

import cv2 

videoCapture = cv2.VideoCapture('123'.avi)

fps = videoCapture.get(cv2.CAP_PROP_FPS)

size = int(int(videoCapture.get(cv2.CAP_PROP_FRAME_WIDTH)),
           int(videoCapture.get(cv2.CAP_PROP_FRAME_HEIGHT)))

videoWriter = cv2.VideoWriter('out.avi',cv2.VideoWriter_fourcc('I','4','2','0'),fps,size)

success,frame = videoCapture.read()

while success:
    videoWriter.write(frame)
    success,frame = videoCapture.read()

捕获摄像头的帧:捕获10s 电脑摄像头视频

import cv2

cameraCapture = cv2.VideoCapture(0)

fps =30

size = (int(cameraCapture.get(cv2.CAP_PROP_FRAME_WIDTH)),
           int(cameraCapture.get(cv2.CAP_PROP_FRAME_HEIGHT)))

videoWriter = cv2.VideoWriter('out.avi',cv2.VideoWriter_fourcc('I','4','2','0'),fps,size)

success,frame = cameraCapture.read()
numFrameRemaining = 10 * fps -1
while success and numFrameRemaining > 0:
    videoWriter.write(frame)
    success,frame = cameraCapture.read()
    numFrameRemaining -= 1
""""
    一组摄像头或一个多头摄像头的使用方法
"""    
# success0 = cameraCapture0.grab()
# success1 = cameraCapture1.grab()
# if success0 and success1:
#     frame0 = cameraCapture0.retrieve()
#     frame1 = cameraCapture1.retrieve()


cameraCapture.release()

图片显示:

import cv2 
import numpy as np

img = cv2.imread('hcl.jpg')
cv2.imshow('hcl',img)
cv2.waitKey()
cv2.destroyAllWindows()

视频显示:

其实这里面代码是通过图片不断更新实现视频效果,可通过注释的sleep看到效果

import cv2 
import numpy as np
import time

clicked = False

def onMouse(event,x,y,flags,param):
    global clicked
    if event == cv2.EVENT_LBUTTONUP:
        clicked = True

cameraCapture = cv2.VideoCapture(0)
cv2.namedWindow('myWindow')
cv2.setMouseCallback('myWindow',onMouse)

print('showing camera feed.click window or press any key to stop')

success,frame = cameraCapture.read()
while success and cv2.waitKey(1) == -1 and not clicked:
    cv2.imshow('myWindow',frame)
    success,frame = cameraCapture.read()
    #time.sleep(1)
    
cv2.destroyWindow('myWindow')
cameraCapture.release()
打开摄像头,tab录制视频,space截图,exit退出
managers.py
import cv2
import numpy
import time


class CaptureManager(object):
    
    def __init__(self, capture, previewWindowManager = None,
                 shouldMirrorPreview = False):
        
        self.previewWindowManager = previewWindowManager
        self.shouldMirrorPreview = shouldMirrorPreview
        
        self._capture = capture
        self._channel = 0
        self._enteredFrame = False
        self._frame = None
        self._imageFilename = None
        self._videoFilename = None
        self._videoEncoding = None
        self._videoWriter = None
        
        self._startTime = None
        self._framesElapsed = int(0)
        self._fpsEstimate = None
    
    @property
    def channel(self):
        return self._channel
    
    @channel.setter
    def channel(self, value):
        if self._channel != value:
            self._channel = value
            self._frame = None
    
    @property
    def frame(self):
        if self._enteredFrame and self._frame is None:
            # As of OpenCV 3.0, VideoCapture.retrieve() no longer supports
            # the channel argument.
            # _, self._frame = self._capture.retrieve(channel = self.channel)
            _, self._frame = self._capture.retrieve()
        return self._frame
    
    @property
    def isWritingImage(self):
        return self._imageFilename is not None
    
    @property
    def isWritingVideo(self):
        return self._videoFilename is not None
    
    def enterFrame(self):
        """Capture the next frame, if any."""
        
        # But first, check that any previous frame was exited.
        assert not self._enteredFrame, \
            'previous enterFrame() had no matching exitFrame()'
        
        if self._capture is not None:
            self._enteredFrame = self._capture.grab()
    
    def exitFrame(self):
        """Draw to the window. Write to files. Release the frame."""
        
        # Check whether any grabbed frame is retrievable.
        # The getter may retrieve and cache the frame.
        if self.frame is None:
            self._enteredFrame = False
            return
        
        # Update the FPS estimate and related variables.
        if self._framesElapsed == 0:
            self._startTime = time.time()
        else:
            timeElapsed = time.time() - self._startTime
            self._fpsEstimate =  self._framesElapsed / timeElapsed
        self._framesElapsed += 1
        
        # Draw to the window, if any.
        if self.previewWindowManager is not None:
            if self.shouldMirrorPreview:
                mirroredFrame = numpy.fliplr(self._frame).copy()
                self.previewWindowManager.show(mirroredFrame)
            else:
                self.previewWindowManager.show(self._frame)
        
        # Write to the image file, if any.
        if self.isWritingImage:
            cv2.imwrite(self._imageFilename, self._frame)
            self._imageFilename = None
        
        # Write to the video file, if any.
        self._writeVideoFrame()
        
        # Release the frame.
        self._frame = None
        self._enteredFrame = False
    
    def writeImage(self, filename):
        """Write the next exited frame to an image file."""
        self._imageFilename = filename
    
    def startWritingVideo(
            self, filename,
            encoding = cv2.VideoWriter_fourcc('M','J','P','G')):
        """Start writing exited frames to a video file."""
        self._videoFilename = filename
        self._videoEncoding = encoding
    
    def stopWritingVideo(self):
        """Stop writing exited frames to a video file."""
        self._videoFilename = None
        self._videoEncoding = None
        self._videoWriter = None
    
    def _writeVideoFrame(self):
        
        if not self.isWritingVideo:
            return
        
        if self._videoWriter is None:
            fps = self._capture.get(cv2.CAP_PROP_FPS)
            if fps <= 0.0:
                # The capture's FPS is unknown so use an estimate.
                if self._framesElapsed < 20:
                    # Wait until more frames elapse so that the
                    # estimate is more stable.
                    return
                else:
                    fps = self._fpsEstimate
            size = (int(self._capture.get(
                        cv2.CAP_PROP_FRAME_WIDTH)),
                    int(self._capture.get(
                        cv2.CAP_PROP_FRAME_HEIGHT)))
            self._videoWriter = cv2.VideoWriter(
                self._videoFilename, self._videoEncoding,
                fps, size)
        
        self._videoWriter.write(self._frame)


class WindowManager(object):
    
    def __init__(self, windowName, keypressCallback = None):
        self.keypressCallback = keypressCallback
        
        self._windowName = windowName
        self._isWindowCreated = False
    
    @property
    def isWindowCreated(self):
        return self._isWindowCreated
    
    def createWindow(self):
        cv2.namedWindow(self._windowName)
        self._isWindowCreated = True
    
    def show(self, frame):
        cv2.imshow(self._windowName, frame)
    
    def destroyWindow(self):
        cv2.destroyWindow(self._windowName)
        self._isWindowCreated = False
    
    def processEvents(self):
        keycode = cv2.waitKey(1)
        if self.keypressCallback is not None and keycode != -1:
            # Discard any non-ASCII info encoded by GTK.
            keycode &= 0xFF
            self.keypressCallback(keycode)
cameo.py
import cv2
from managers import WindowManager, CaptureManager

class Cameo(object):
    
    def __init__(self):
        self._windowManager = WindowManager('Cameo',
                                            self.onKeypress)
        self._captureManager = CaptureManager(
            cv2.VideoCapture(0), self._windowManager, True)
    
    def run(self):
        """Run the main loop."""
        self._windowManager.createWindow()
        while self._windowManager.isWindowCreated:
            self._captureManager.enterFrame()
            frame = self._captureManager.frame
            
            if frame is not None:
                # TODO: Filter the frame (Chapter 3).
                pass
            
            self._captureManager.exitFrame()
            self._windowManager.processEvents()
    
    def onKeypress(self, keycode):
        """Handle a keypress.
        
        space  -> Take a screenshot.
        tab    -> Start/stop recording a screencast.
        escape -> Quit.
        
        """
        if keycode == 32: # space
            self._captureManager.writeImage('screenshot.png')
        elif keycode == 9: # tab
            if not self._captureManager.isWritingVideo:
                self._captureManager.startWritingVideo(
                    'screencast.avi')
            else:
                self._captureManager.stopWritingVideo()
        elif keycode == 27: # escape
            self._windowManager.destroyWindow()

if __name__=="__main__":
    Cameo().run()

你可能感兴趣的:(opencv)