save image cv2.imwrite()

Explained Cv2.Imwrite() Function In Detail | Save Image

OpenCV library has powerful function named as cv2.imwrite(). Which saves the NumPy array in the form of an Image.

cv2.imwrite() function takes any size of NumPy array and saves it as an image in JPEG or PNG file format.

save image cv2.imwrite()

How to save image or NumPy array as image

Save Numpy Array

#For detail Explanation watch prime video: video link >>> https://youtu.be/6VqbeozUgWQ

import cv2
import numpy as np
import os

rand_array = np.random.randint(255, size = (300,600,3))

cv2.imwrite("rand_np_array.png", rand_array) # imwrite(filename, img[, params])

img = cv2.imread("rand_np_array.png")
cv2.imshow('image', img)

cv2.waitKey(0)
cv2.destroyAllWindows()

Save Image

import cv2
import numpy as np
import os

img_path = 'model.jpg'

img = cv2.imread(img_path)
cv2.imshow('image', img)

cv2.imwrite("model_write.png", img)

cv2.waitKey(0)
cv2.destroyAllWindows()

Save Images from Video

import cv2
import numpy as np
import os

video_path = r"C:\Users\kashz\AI Life\AI Projects - IAIP, PTs (Web + Channel)\02 OpenCV\007 Live Face and Eye Detection\school_girl.mp4"

os.mkdir("video_to_image") # create directory

cap = cv2.VideoCapture(video_path) # capture video

img_count = 1
while cap.isOpened():
    ret, frame = cap.read() # read video frame
    
    if not ret:
        print("Unable to read frame")
        break
    
    is_img_write = cv2.imwrite(f"video_to_image\image{img_count}.jpeg", frame)
    
    if is_img_write:
        print(f'image save at video_to_image\image{img_count}.jpeg')
        
    cv2.imshow("video", frame )
    
    cv2.waitKey(25) & 0xff == ord('q')
    img_count += 1
    
cap.release()
cv2.destroyAllWindows()

Leave a Reply