- Сохранение изображения с помощью cv2.imwrite() в OpenCV Python
- Синтаксис
- Пример 1
- Пример 2: со случайными значениями
- Cv2 save image python
- Python OpenCV cv2.imwrite() – Save Image
- Syntax of cv2 imwrite()
- Examples
- 1. Save matrix as image using cv2.imwrite()
- 2. Save image created with random pixel values using cv2.imwrite()
- Summary
Сохранение изображения с помощью cv2.imwrite() в OpenCV Python
Чтобы сохранить изображение в локальное хранилище с помощью Python, используйте функцию cv2.imwrite() в библиотеке OpenCV.
Синтаксис
Где, path – это полный путь к выходному файлу, в который вы хотите записать массив numpy изображений.
cv2.imwrite() возвращает логическое значение. true, если изображение успешно записано, и false, если изображение не было успешно записано по указанному локальному пути.
Пример 1
В этом примере мы прочитаем изображение, преобразуем его, а затем сохраним изображение в постоянном файловом хранилище с помощью метода imwrite().
import cv2 #read image as grey scale img = cv2.imread('D:/image-1.png') #do some transformations on img #save matrix/array as image file isWritten = cv2.imwrite('D:/image-2.png', img) if isWritten: print('Image is successfully saved as file.')
Image is successfully saved as file.
Пример 2: со случайными значениями
В этом примере мы напишем массив numpy как изображение, используя функцию cv2.imwrite(). Для этого мы создадим массив с тремя каналами для красного, зеленого и синего, содержащий случайные значения. В общих случаях мы читаем изображение, применяем некоторые преобразования к массиву и затем записываем изображение в локальное хранилище. Но в этом примере мы будем придерживаться массива со случайными значениями.
import cv2 import numpy as np img = np.random.randint(255, size=(300, 600, 3)) isWritten = cv2.imwrite('D:/image-2.png', img) if isWritten: print('The image is successfully saved.')
The image is successfully saved.
Ниже приведено изображение, созданное со случайными значениями.
В этом руководстве на примерах Python мы узнали, как использовать cv2.imwrite() для сохранения массива numpy в виде изображения.
Cv2 save image python
- Image Resizing using OpenCV | Python
- Python OpenCV | cv2.erode() method
- Python | Image blurring using OpenCV
- Python OpenCV | cv2.copyMakeBorder() method
- Python | Grayscaling of Images using OpenCV
- Image Processing in Python (Scaling, Rotating, Shifting and Edge Detection)
- Erosion and Dilation of images using OpenCV in python
- OpenCV Python Program to analyze an image using Histogram
- Histograms Equalization in OpenCV
- Python | Thresholding techniques using OpenCV | Set-1 (Simple Thresholding)
- Python | Thresholding techniques using OpenCV | Set-2 (Adaptive Thresholding)
- Python | Thresholding techniques using OpenCV | Set-3 (Otsu Thresholding)
- OpenCV: Segmentation using Thresholding
- Python OpenCV | cv2.cvtColor() method
- Filter Color with OpenCV
- Python | Denoising of colored images using opencv
- Python | Visualizing image in different color spaces
- Find Co-ordinates of Contours using OpenCV | Python
- Python | Bilateral Filtering
- Image Inpainting using OpenCV
- Python | Intensity Transformation Operations on Images
- Python | Image Registration using OpenCV
- Python | Background subtraction using OpenCV
- Background Subtraction in an Image using Concept of Running Average
- Python | Foreground Extraction in an Image using Grabcut Algorithm
- Python | Morphological Operations in Image Processing (Opening) | Set-1
- Python | Morphological Operations in Image Processing (Closing) | Set-2
- Python | Morphological Operations in Image Processing (Gradient) | Set-3
- Image segmentation using Morphological operations in Python
- Image Translation using OpenCV | Python
- Image Pyramid using OpenCV | Python
- Python | Program to extract frames using OpenCV
- Displaying the coordinates of the points clicked on the image using Python-OpenCV
- White and black dot detection using OpenCV | Python
- Python | OpenCV BGR color palette with trackbars
- Draw a rectangular shape and extract objects using Python’s OpenCV
- Invisible Cloak using OpenCV | Python Project
- ML | Unsupervised Face Clustering Pipeline
- Saving Operated Video from a webcam using OpenCV
- Face Detection using Python and OpenCV with webcam
- Opening multiple color windows to capture using OpenCV in Python
- Python | Play a video in reverse mode using OpenCV
- Template matching using OpenCV in Python
- Cartooning an Image using OpenCV – Python
- Vehicle detection using OpenCV Python
- Count number of Faces using Python – OpenCV
- Live Webcam Drawing using OpenCV
- Detect and Recognize Car License Plate from a video in real time
- Build GUI Application Pencil Sketch from Photo in Python
- Python OpenCV – Drowsiness Detection
- Face Alignment with OpenCV and Python
- Age Detection using Deep Learning in OpenCV
- Right and Left Hand Detection Using Python
- OpenCV Python: How to detect if a window is closed?
- Save frames of live video with timestamps – Python OpenCV
- Detecting low contrast images with OpenCV, scikit-image, and Python
- Animate image using OpenCV in Python
- Drawing a cross on an image with OpenCV
- Blur and anonymize faces with OpenCV and Python
- Face detection using Cascade Classifier using OpenCV-Python
- Real time object color detection using OpenCV
- Python – Writing to video with OpenCV
- Add image to a live camera feed using OpenCV-Python
- Face and Hand Landmarks Detection using Python – Mediapipe, OpenCV
- Emotion Based Music Player – Python Project
- Realtime Distance Estimation Using OpenCV – Python
- Webcam QR code scanner using OpenCV
- Color Identification in Images using Python – OpenCV
- Real-Time Edge Detection using OpenCV in Python | Canny edge detection method
- Opencv Python program for Face Detection
- Image Resizing using OpenCV | Python
- Python OpenCV | cv2.erode() method
- Python | Image blurring using OpenCV
- Python OpenCV | cv2.copyMakeBorder() method
- Python | Grayscaling of Images using OpenCV
- Image Processing in Python (Scaling, Rotating, Shifting and Edge Detection)
- Erosion and Dilation of images using OpenCV in python
- OpenCV Python Program to analyze an image using Histogram
- Histograms Equalization in OpenCV
- Python | Thresholding techniques using OpenCV | Set-1 (Simple Thresholding)
- Python | Thresholding techniques using OpenCV | Set-2 (Adaptive Thresholding)
- Python | Thresholding techniques using OpenCV | Set-3 (Otsu Thresholding)
- OpenCV: Segmentation using Thresholding
- Python OpenCV | cv2.cvtColor() method
- Filter Color with OpenCV
- Python | Denoising of colored images using opencv
- Python | Visualizing image in different color spaces
- Find Co-ordinates of Contours using OpenCV | Python
- Python | Bilateral Filtering
- Image Inpainting using OpenCV
- Python | Intensity Transformation Operations on Images
- Python | Image Registration using OpenCV
- Python | Background subtraction using OpenCV
- Background Subtraction in an Image using Concept of Running Average
- Python | Foreground Extraction in an Image using Grabcut Algorithm
- Python | Morphological Operations in Image Processing (Opening) | Set-1
- Python | Morphological Operations in Image Processing (Closing) | Set-2
- Python | Morphological Operations in Image Processing (Gradient) | Set-3
- Image segmentation using Morphological operations in Python
- Image Translation using OpenCV | Python
- Image Pyramid using OpenCV | Python
- Python | Program to extract frames using OpenCV
- Displaying the coordinates of the points clicked on the image using Python-OpenCV
- White and black dot detection using OpenCV | Python
- Python | OpenCV BGR color palette with trackbars
- Draw a rectangular shape and extract objects using Python’s OpenCV
- Invisible Cloak using OpenCV | Python Project
- ML | Unsupervised Face Clustering Pipeline
- Saving Operated Video from a webcam using OpenCV
- Face Detection using Python and OpenCV with webcam
- Opening multiple color windows to capture using OpenCV in Python
- Python | Play a video in reverse mode using OpenCV
- Template matching using OpenCV in Python
- Cartooning an Image using OpenCV – Python
- Vehicle detection using OpenCV Python
- Count number of Faces using Python – OpenCV
- Live Webcam Drawing using OpenCV
- Detect and Recognize Car License Plate from a video in real time
- Build GUI Application Pencil Sketch from Photo in Python
- Python OpenCV – Drowsiness Detection
- Face Alignment with OpenCV and Python
- Age Detection using Deep Learning in OpenCV
- Right and Left Hand Detection Using Python
- OpenCV Python: How to detect if a window is closed?
- Save frames of live video with timestamps – Python OpenCV
- Detecting low contrast images with OpenCV, scikit-image, and Python
- Animate image using OpenCV in Python
- Drawing a cross on an image with OpenCV
- Blur and anonymize faces with OpenCV and Python
- Face detection using Cascade Classifier using OpenCV-Python
- Real time object color detection using OpenCV
- Python – Writing to video with OpenCV
- Add image to a live camera feed using OpenCV-Python
- Face and Hand Landmarks Detection using Python – Mediapipe, OpenCV
- Emotion Based Music Player – Python Project
- Realtime Distance Estimation Using OpenCV – Python
- Webcam QR code scanner using OpenCV
- Color Identification in Images using Python – OpenCV
- Real-Time Edge Detection using OpenCV in Python | Canny edge detection method
- Opencv Python program for Face Detection
Python OpenCV cv2.imwrite() – Save Image
In our previous tutorial – cv2 imread(), we learned to read an image into a matrix. You may transform this matrix by using some algorithms. Then it may be required to save this matrix as an image.
In this tutorial, we will learn how to save an array as image in file system.
To save image to local storage using Python, use cv2.imwrite() function on OpenCV library.
Syntax of cv2 imwrite()
The syntax of imwrite() function is:
where path is the complete path of the output file to which you would like to write the image numpy array.
cv2.imwrite() returns a boolean value. True if the image is successfully written and False if the image is not written successfully to the local path specified.
Examples
1. Save matrix as image using cv2.imwrite()
In this example, we will read an image, transform it and then save the image to persistent file storage using imwrite() method.
Python Program
import cv2 #read image as grey scale img = cv2.imread('D:/image-1.png') #do some transformations on img #save matrix/array as image file isWritten = cv2.imwrite('D:/image-2.png', img) if isWritten: print('Image is successfully saved as file.')
Image is successfully saved as file.
2. Save image created with random pixel values using cv2.imwrite()
In this example, we will write a numpy array as image using cv2.imwrite() function. For that, we will create a numpy array with three channels for Red, Green and Blue containing random values.
In general cases, we read image using cv2.imread(), apply some transformations on the array and then write the image to the local storage. But in this example, we will stick to the array with random values.
Python Program
import cv2 import numpy as np img = np.random.randint(255, size=(300, 600, 3)) isWritten = cv2.imwrite('D:/image-2.png', img) if isWritten: print('The image is successfully saved.')
The image is successfully saved.
Following is the image that is generated with the random values.
Summary
In this Python OpenCV Tutorial, we have seen how to use cv2.imwrite() to save numpy array as an image.