Python中的图像处理中的形态学操作
形态学操作可用于提取对于区域形状的描述和表示有用的图像组件。形态学操作是依赖于图像形状的基本任务。它通常在二值图像上进行。它需要两个数据源,第一个是输入图像,第二个称为结构化组件。
形态学运算符能够接受输入图像和结构化组件作为输入。然后,将这两个元素与集合运算符组合。根据图像的形状特征来处理图像输入的对象。这些可以由结构化部分进行编码。
开运算 类似于侵蚀操作,因为它会从前景像素的边缘移除亮的前景像素。该操作的结果是保护前景区域,该区域类似于结构化组件,甚至完全包含结构化组件,同时移除前景像素中的所有其他区域。开运算操作被用于消除图像内部噪声。
开运算是侵蚀操作后跟膨胀操作。
所需模块和库:
在图像处理中执行形态操作,我们将需要以下模块:
1. cv2
安装: !pip3 install cv2
2. NumPy
安装: !pip3 install numpy
语法:
cv2morphology的语法是:
cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel)
参数:
- image: 它接受输入图像数组。
- MORPH_OPEN: 用于应用形态学开操作。
- kernel: 用于形态学操作的结构元素。
下面是用于解释开放形态学操作的Python代码 –
代码:
# First, we will import the required libraries:
import cv2 as CV
import numpy as nmp
# here, it will return video from the first webcam on our computer.
screenRead1 = CV.VideoCapture(0)
# now, it will loop runs if capturing has been initialized.
while(1):
# now, it is reading frames from a camera
_, image = screenRead1.read()
# Converting to HSV color space because OCV only reads colors as BGR
# and the frame is converted to hsv
hsv = CV.cvtColor(image, CV.COLOR_BGR2HSV)
# here, we will define the range of masking
blue_1 = nmp.array([111, 52, 52])
blue_2 = n,p.array([131, 257, 257])
# Now, we will initialize the mask forconvoluting over input image
mask = CV.inRange(hsv, blue_1, blue_2)
# then, we will pass the bitwise_and over each pixel convoluted
res = CV.bitwise_and(image, image, mask = mask)
# Here, we will define the kernel that is Structuring element
kernel = nmp.ones((5, 5), nmp.uint8)
# Now, we will define the opening function over the image and structuring # element
opening = CV.morphologyEx(mask, CV.MORPH_OPEN, kernel)
# The mask and opening operation is shown in the window
CV.imshow('Mask', mask)
CV.imshow('Opening', opening)
# Now, it will wait for 'a' key to stop the program
if CV.waitKey(1) & 0xFF == ord('a'):
break
# De-allocate any associated memory usage
CV.destroyAllWindows()
# At last, we will close the window and Release webcam
screenRead.release()
输出
输入图像
面罩:
输出框架
系统识别指定的蓝色书籍作为输入,并借助Opening功能移除和消除感兴趣区域内的噪声。