Skip to content

Commit

Permalink
Merge pull request #12 from AAnirudh07/main
Browse files Browse the repository at this point in the history
add image & video reading tutorial
  • Loading branch information
diffrxction authored Oct 2, 2022
2 parents 294262c + 8132b17 commit dbb9234
Show file tree
Hide file tree
Showing 9 changed files with 655 additions and 0 deletions.
62 changes: 62 additions & 0 deletions Image Processing/Reading-Image-Video/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
## Reading-Image-Video

### Reading an image using OpenCV
- Images can be read using OpenCV's imread() function.

**Syntax:** cv2.imread(path, flag)

**Parameters:**
path: A string representing the path of the image to be read.
flag: It specifies the way in which image should be read. It’s default value is cv2.IMREAD_COLOR

**Return Value:** This method returns an image object that is loaded from the specified file.

For more implementation details, please refer to the associated Python notebook: `read_image_opencv.ipynb`.

### Reading an image using PIL
- Images can also be read using the Pillow's Image() function.
**Syntax:** PIL.Image(path,mode="r")

**Parameters:**
path: A string representing the path of the image to be read.
mode – The mode. If given, this argument must be “r”. Hence, this parameter is superfluous.

**Return Value:** This method returns an image object that is loaded from the specified file.

For more implementation details, please refer to the associated Python notebook: `read_image_pil.ipynb`.

### Reading videos using OpenCV
- A video is simply a sequence of frames.
- OpenCV provides functions for reading video streams as a sequence of frames.
- OpenCV's video reading methods are widely used.

1. Reading a video using OpenCV

**Syntax - I:** cv2.VideoCapture(path)

**Parameters:**
path: A string representing the path of the image to be read.

**Return Value:** This method returns a VideoCapture object that can be used to read the file.

**Syntax - II:** \<\<VideoCapture object\>\>.read()

**Parameters:**
path: A string representing the path of the image to be read.

**Return Value:** This method returns two values:
1. ret - a flag indicating if the last frame has been read. This value is always false till the last frame.
2. frame - frame of a video

For more implementation details, please refer to the associated Python script: `read_video_opencv.py`.

2. Reading webcam stream using OpenCV
- Reading a webcam stream is almost the same as reading a video.
- First, the path attribute in the VideoCapture() function has to be set to 0 to refer to the default computer webcam.
- Second, the ret value in the read() function does not matter. The stream is stopped as and when the user wishes to.


### BONUS: Speed up frame processing using multi-threading
- Despite its evident advantages, OpenCV is often very slow when it comes to reading video streams. This is because OpenCV reads a video frame-by-frame.
- The frame rate can be increased by performing the read() method in a separate thread. The main execution thread can then be use the frames generated by the other thread.
- A popular open-source library, imutils, uses this concept to speed up frame reading. Please refer to the associated python script for more details. (`read_video_imutils.py`)
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file not shown.
363 changes: 363 additions & 0 deletions Image Processing/Reading-Image-Video/read_image_opencv.ipynb

Large diffs are not rendered by default.

158 changes: 158 additions & 0 deletions Image Processing/Reading-Image-Video/read_image_pil.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "markdown",
"source": [
"### This python notebook shows how to read images using PIL's Image() function. \n",
"Image() supports various file formats including, but not limited to, .bmp, .webp, .jpg, .jpeg, and .png."
],
"metadata": {
"id": "QvWIh7h0hurM"
}
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"id": "992nZ6S0hk66"
},
"outputs": [],
"source": [
"#Import the necessary libraries\n",
"import os\n",
"from google.colab import drive\n",
"from google.colab.patches import cv2_imshow #used to display images on colab\n",
"from PIL import Image"
]
},
{
"cell_type": "code",
"source": [
"#Connect to Google Drive\n",
"drive.mount('/content/drive',force_remount=True)\n",
"os.chdir('/content/drive/My Drive')\n",
"print(\"Change successful.\")"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "3gS6Rx6ch6n7",
"outputId": "45854639-8687-4771-f834-7c7b43990f64"
},
"execution_count": 2,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Mounted at /content/drive\n",
"Change successful.\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"#### Reading an image using Image() [Image(path)]"
],
"metadata": {
"id": "3-doVYQ4h80E"
}
},
{
"cell_type": "code",
"source": [
"img = Image.open(\"python_logo.png\")\n",
"img #this work-around is only for Google Colab. On your local machines please use img.show() to display the image."
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 242
},
"id": "Jw5KsuFWiJeT",
"outputId": "fe1e289b-a5d0-4900-8e41-b4c1e55eed5b"
},
"execution_count": 5,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"<PIL.PngImagePlugin.PngImageFile image mode=P size=225x225 at 0x7FEAD36C64D0>"
],
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAADAFBMVEX///9HldH/yFFZn9bMzMzMpE7Jycn/ylE/lNXIoU7QpUeTnZj39/f/yE1AktD/zWLJzNGLt9//2JD/ykc2ktbVun3xyXuUveKLpLN2ptDRz8xaoNb/3Jnt7e1pp9n8yFzd3d3u9fs5dqbY2Nj0ynPC2e7Y6PV9s95OmtTp8vnN4fH/5rb3ymrVzLvRzMLKnkClyef/897/+/P/03fwvEzdzKvx26/i5enJmi/czK3iy6Dpy4+10uuixeU5icM2f7W9z95gjrQsb6FRhrCsw9dzmbuLq8L/4qj/7cqXq6+mrqG4rob/14XetVWhoIj/68a9pGi6qn26omngr0WLrcyuvsvdv33o3MXpszXcwIvUr2NbW1tcXFxdXV1eXl5fX19gYGBhYWFiYmJjY2NkZGRlZWVmZmZnZ2doaGhpaWlqampra2tsbGxtbW1ubm5vb29wcHBxcXFycnJzc3N0dHR1dXV2dnZ3d3d4eHh5eXl6enp7e3t8fHx9fX1+fn5/f3+AgICBgYGCgoKDg4OEhISFhYWGhoaHh4eIiIiJiYmKioqLi4uMjIyNjY2Ojo6Pj4+QkJCRkZGSkpKTk5OUlJSVlZWWlpaXl5eYmJiZmZmampqbm5ucnJydnZ2enp6fn5+goKChoaGioqKjo6OkpKSlpaWmpqanp6eoqKipqamqqq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ULIfGMYnbxNHUhk2vnOuIykIrrxdEwKb4zigEiusiRVQPlBl9RdhFcmw59J4Q2OSueijkxzQXHTtMTJRPWLjjqukwm/jIQvpdqkusgwjO758CJfb+c8/yIu167nL4bn3ccqoNp6+RGyp7WH6qIFxU2zEidSnRNVmQx3SHXRwhoqT43T2upNyZYqtbkaqocap1qltN52M7LZkh+hFU4SiUQikUgkEolEIpFIJBKJRPIv5P/y2U9pldfRxgAAAABJRU5ErkJggg==\n"
},
"metadata": {},
"execution_count": 5
}
]
},
{
"cell_type": "markdown",
"source": [
"#### PIL Image() mode attribute\n",
"The mode attribute of the image tells the type and depth of the pixel in the image. A 1-bit pixel has a range of 0-1, and an 8-bit pixel has a range of 0-255. There are different modes provided by this module:\n",
"\n",
"1 ==> 1-bit pixels, black and white\n",
"\n",
"L ==> 8-bit pixels, Greyscale\n",
"\n",
"P ==> 8-bit pixels, mapped to any other mode using a color palette\n",
"\n",
"RGB ==> 3×8-bit pixels, true color\n",
"\n",
"RGBA ==> 4×8-bit pixels, true color with transparency mask"
],
"metadata": {
"id": "nzsrfm_alTTU"
}
},
{
"cell_type": "code",
"source": [
"img.mode"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 36
},
"id": "270Dia4njPlJ",
"outputId": "92bd14a7-82d4-4730-af51-e465749c6175"
},
"execution_count": 6,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'P'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 6
}
]
}
]
}
23 changes: 23 additions & 0 deletions Image Processing/Reading-Image-Video/read_video_imutils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#This Python script shows how to use the imutils library to speed up frame reading

#Import the necessary libraries
import cv2
import time
from imutils.video import WebcamVideoStream


#Initialize the WebcamVideoStream object; src=0 refers to the webcam
vs = WebcamVideoStream(src=0).start()

while True:
imutils_frame= vs.read()

cv2.imshow("IMUTILS",imutils_frame)
key = cv2.waitKey(1)
if key == 27: #esc key stops the process
break


## When everything done, release the object and close all opened windows
vs.stop()
cv2.destroyAllWindows()
27 changes: 27 additions & 0 deletions Image Processing/Reading-Image-Video/read_video_opencv.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#This Python script shows how to read a video using OpenCV

#Import the necessary libraries
import cv2

#Initialize the VideoCapture object
cap = cv2.VideoCapture('assets/video.mp4')

# Check if camera opened successfully
if (cap.isOpened()== False):
print("Error opening video")

while cap.isOpened():
ret, frame = cap.read()
if ret:
# Display the resulting frame
cv2.imshow('Video',frame)
# Press Q on keyboard to exit (or) move to the next frame after 1 milliseconds
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break

# When everything done, release the video capture object and close all opened windows
cap.release()
cv2.destroyAllWindows()

22 changes: 22 additions & 0 deletions Image Processing/Reading-Image-Video/read_webcam_opencv.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#This Python script shows how to read a video using OpenCV

#Import the necessary libraries
import cv2

#Initialize the VideoCapture object
cap = cv2.VideoCapture(0)

# Check if camera opened successfully
if (cap.isOpened()== False):
print("Error opening video")

while True:
_, frame = cap.read()
cv2.imshow('Video',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break

# When everything done, release the video capture object and close all opened windows
cap.release()
cv2.destroyAllWindows()

0 comments on commit dbb9234

Please sign in to comment.