- Opencv python получить цвет пикселя
- Базовые операции OpenCV с изображениями на примерах
- Доступ и изменение значений пикселей в OpenCV
- Доступ к свойствам изображения в OpenCV
- ROI (Region of Interest) изображения
- Разделение и объединение каналов изображения в OpenCV
- Создание границ для изображений
- Изменение цвета изображения
- OpenCV cvtColor
- Параметры:
Opencv 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
Базовые операции OpenCV с изображениями на примерах
В этом уроке мы изучим основные базовые операции OpenCV, связанные с изображениями. Мы собираемся обсудить следующие темы.
- Доступ к значениям пикселей и их изменение
- Доступ к свойствам изображения
- Настройка области изображения
- Разделение и объединение изображений
- Изменение цвета изображения
Доступ и изменение значений пикселей в OpenCV
Мы можем получить значение пикселя по его координатам строки и столбца. Оно возвращает массив значений синего, зеленого и красного цвета изображения BGR и соответствующую интенсивность для изображения в градациях серого. Сначала нам нужно загрузить образ BGR.
import numpy as np import cv2 img = cv2.imread("C:\Users\DEVANSH SHARMA\cat.jpeg",1) pixel = img[100,100] print(pixel)
Доступ к свойствам изображения в OpenCV
Необходимо знать размер изображения для работы с приложением для обработки изображений. В OpenCV изображения обычно хранятся в Numpy ndarray. Чтобы получить форму или размер изображения, используйте ndarray.shape. Затем мы можем использовать позицию индекса, чтобы получить высоту, ширину и количество каналов.
Рассмотрим следующий пример:
import cv2 # read image img = cv2.imread(r'C:\Users\DEVANSH SHARMA\cat.jpeg',1) # height, width, number of channels in image height = img.shape[0] width = img.shape[1] channels = img.shape[2] size1 = img.size print('Image Dimension : ',dimensions) print('Image Height : ',height) print('Image Width : ',width) print('Number of Channels : ',channels) print('Image Size :', size1)
Image Dimension : (4, 1, 3) Image Height : 4 Image Width : 1 Number of Channels : 3 Image Size : 12
ROI (Region of Interest) изображения
Иногда нам нужно работать с некоторыми областями изображения. Как мы обсуждали в предыдущем уроке, распознавание лиц происходит по всему изображению. Когда лицо получено, мы выбираем только область лица и ищем глаза внутри нее, а не ищем все изображение. Это повышает точность и производительность, поскольку глаза всегда смотрят на лицо и не нужно искать по всему изображению.
На изображении выше, если нам нужно выбрать мяч, нам потребуется только выбрать область шара.
Разделение и объединение каналов изображения в OpenCV
При необходимости каналы BGR изображения можно разделить на их плоскости. Затем отдельные каналы можно снова объединить из изображения BGR. Это можно сделать следующим образом:
b,g,r = cv2.split(img) img = cv2.merge((b,g,r))
Примечание. Функция cv2.split() работает медленно. Индексация Numpy довольно эффективна, и ее следует использовать, если это возможно.
Создание границ для изображений
OpenCV предоставляет функцию cv2.copyMakeBorder() для создания рамки вокруг изображения, что-то вроде фоторамки. Синтаксис функции приведен ниже.
cv2.copyMakeBorder(src,top,bottom,left,right,border type)
- src – обозначает входное изображение.
- top, bottom, left, right – определяет ширину границы в количестве пикселей в соответствующем направлении.
- borderType — определяет, какую границу нужно добавить. Бордюр может быть следующих видов.
- value – цвет границы, если тип границы cv.BORDER_CONSTANT.
Рассмотрим следующий пример:
import cv2 as cv import numpy as np from matplotlib import pyplot as plt BLUE = [255,0,0] img1 = cv.imread(r'C:\User\DEVANSH SHARMA\flower.jpg',1) replicate = cv.copyMakeBorder(img1,10,10,10,10,cv.BORDER_REPLICATE) reflect = cv.copyMakeBorder(img1,10,10,10,10,cv.BORDER_REFLECT) reflect101 = cv.copyMakeBorder(img1,10,10,10,10,cv.BORDER_REFLECT_101) wrap = cv.copyMakeBorder(img1,10,10,10,10,cv.BORDER_WRAP) constant= cv.copyMakeBorder(img1,10,10,10,10,cv.BORDER_CONSTANT,value=BLUE) plt.subplot(231),plt.imshow(img1,'gray'),plt.title('ORIGINAL') plt.subplot(232),plt.imshow(replicate,'gray'),plt.title('REPLICATE') plt.subplot(233),plt.imshow(reflect,'gray'),plt.title('REFLECT') plt.subplot(234),plt.imshow(reflect101,'gray'),plt.title('REFLECT_101') plt.subplot(235),plt.imshow(wrap,'gray'),plt.title('WRAP') plt.subplot(236),plt.imshow(constant,'gray'),plt.title('CONSTANT') plt.show()
Изменение цвета изображения
OpenCV cvtColor
CvtColor используется для преобразования изображения из одного цветового пространства в другое. Синтаксис следующий:
Параметры:
- src — используется для ввода изображения: 8-битное беззнаковое.
- dst — используется для отображения изображения в качестве вывода. Выходное изображение будет того же размера и глубины, что и входное изображение.
- code – код преобразования цветового пространства.
Рассмотрим следующий пример:
# importing cv2 import cv2 # path of the input image path =(r'C:\Users\DEVANSH SHARMA\cat.jpeg') # Reading an image in default mode src = cv2.imread(path) # Window name in which image is displayed window_name = 'Image' # Using cv2.cvtColor() method # Using cv2.COLOR_BGR2GRAY color space for convert BGR image to grayscale # conversion code image = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY ) # Displaying the image cv2.imshow(window_name, image)