OpenCV: Difference between revisions

From David's Wiki
Line 22: Line 22:
# Write your output image
# Write your output image
cv2.imwrite("my_modified_image.png", my_image)
cv2.imwrite("my_modified_image.png", my_image)
</syntaxhighlight>
===Resizing an Image===
[https://docs.opencv.org/master/da/d6e/tutorial_py_geometric_transformations.html Reference]
<syntaxhighlight lang="bash">
import numpy as np
import cv2
img = cv2.imread('messi5.jpg')
new_img = cv2.resize(img, (500,200), interpolation = cv.INTER_CUBIC)
</syntaxhighlight>
</syntaxhighlight>



Revision as of 20:49, 27 December 2019

OpenCV is a very popular computer vision and image processing library.
There are bindings for C++, Java, JavaScript, and Python

Installation

  • Download Python 3
pip install opencv-python


Usage

Getting Started

import cv2

# Use 0 to read in grayscale
my_image = cv2.imread("my_image.png", 0)

# Perform some modification
# Do your machine learning here

# Write your output image
cv2.imwrite("my_modified_image.png", my_image)


Resizing an Image

Reference

import numpy as np
import cv2

img = cv2.imread('messi5.jpg')
new_img = cv2.resize(img, (500,200), interpolation = cv.INTER_CUBIC)

Video

Reading Video

video_capture = cv2.VideoCapture(path.join(videos_folder, video_filename))
if not video_capture.isOpened():
    print("Error opening video stream or file")
    sys.exit(0)

frame_num = 0
while video_capture.isOpened() and frame_num < 30:
    ret, frame = video_capture.read()
    if ret:
        cv2.imshow('Frame', frame)

        frame_num = frame_num + 1
        if cv2.waitKey(25) & 0xFF == ord('q'):
            break
    else:
        break

Writing Video

C++ Video Write
Note that OpenCV does not handle audio.

output_video = cv2.VideoWriter()
codec = cv2.VideoWriter_fourcc(*"avc1")
fps = 15
image_size = (100, 100)
output_video.open("video_output.mp4", codec, fps, image_size, True)
if not output_video.isOpened():
    print("Error opening output video")

# Write all of your frames
# while have_frames:
#   output_video.write(my_frame)

# Release the video
output_video.release()

Resources