OpenCV——Summary of "Introduction to Commonly Used Functions" in "License Plate Recognition"

1.

cv2.getStructuringElement(cv2.MORPH_RECT, (10, 10))

element = cv2.getStructuringElement(shape, ksize[, anchor])

A structuring element for creating morphological operations.

Parameter explanation:

shape: The shape of the structuring element, which can be one of the following values:
cv2.MORPH_RECT: Rectangular structuring element.
cv2.MORPH_CROSS: Cross structure element.
cv2.MORPH_ELLIPSE: Ellipse structuring element.

ksize: the size of the structural element, indicating the width and height of the structural element. It can be an integer, representing the side length of a square structure element; or a tuple (width, height), representing the width and height of a rectangle structure element.

anchor: optional parameter, indicating the anchor point position of the structural element, the default is (-1, -1), which means setting the anchor point at the center of the structural element.
return value:

element: The created structural element, which can be used for morphological operations (such as expansion, erosion, opening operation, closing operation, etc.).

2.

cv2.morphologyEx(img_edge, cv2.MORPH_CLOSE, kernel)#进行闭运算,sd。首先进行膨胀后进行腐蚀操作,去除白色中的黑色点。

dst = cv2.morphologyEx(src, op, kernel[, dst[, anchor[, iterations[, borderType[, borderValue]]]]])

One of the morphological operation functions, used to perform morphological operations on images.

Parameter explanation:

src: The input image, which can be single-channel (grayscale) or multi-channel (color).
op: Morphological operation type, can be one of the following values:
cv2.MORPH_ERODE: Erosion operation.
cv2.MORPH_DILATE: Dilation operation.
cv2.MORPH_OPEN: Open operation (corrosion first and then expansion).
cv2.MORPH_CLOSE: Close operation (expand first and then corrode).
cv2.MORPH_GRADIENT: Morphological gradient (difference between dilated and eroded images).
cv2.MORPH_TOPHAT: Top hat operation (the difference between the original image and the result of the opening operation).
cv2.MORPH_BLACKHAT: Black hat operation (the difference between the result of the closed operation and the original image).
kernel: The structural element (kernel) is used to specify the scope and shape of the morphological operation.

dst: optional parameter, the output image has the same size and number of channels as the input image.

anchor: optional parameter, the position of the anchor point, the default is (-1, -1), indicating that the anchor point is set at the center of the structural element.

iterations: optional parameter, specifies the number of iterations of the morphological operation, the default is 1.

borderType: optional parameter, boundary extension type, default is cv2.BORDER_CONSTANT.

borderValue: optional parameter, border padding value, default is 0.
return value:

dst: The result image of the morphological operation.

3.

cv2.threshold(img_opening, 0, 255, cv2.THRESH_BINARY)#可以理解为简单滤波

ret, thresh = cv2.threshold(src, thresh, maxval, type[, dst])

Used to binarize the image.
Parameter explanation:

src: The input image, usually a grayscale image (single-channel image).
thresh: Threshold to compare the pixel values ​​of the image to.
maxval: When the pixel value is greater than the threshold, set the pixel value.
type: Binarization type, which specifies how to compare and assign pixel values ​​to thresholds. The commonly used types are:
cv2.THRESH_BINARY: The pixel value greater than the threshold is set to maxval, and the pixel value less than or equal to the threshold is set to 0.
cv2.THRESH_BINARY_INV: Pixel values ​​greater than the threshold are set to 0, and pixel values ​​less than or equal to the threshold are set to maxval.
cv2.THRESH_TRUNC: Pixel values ​​greater than the threshold are set to the threshold, and pixel values ​​less than or equal to the threshold remain unchanged.
cv2.THRESH_TOZERO: Pixel values ​​greater than the threshold remain unchanged, and pixel values ​​less than or equal to the threshold are set to 0.
cv2.THRESH_TOZERO_INV: Pixel values ​​greater than the threshold are set to 0, and pixel values ​​less than or equal to the threshold remain unchanged.
dst: optional parameter, the output binarized image, which has the same size and type as the input image src.
return value:

ret: the calculated threshold.
thresh: Binarized image.
sample code

import cv2

# 读取灰度图像
image = cv2.imread('image.jpg', 0)

# 进行二值化处理
ret, thresh = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)

# 显示原图和二值化图像
cv2.imshow('Original Image', image)
cv2.imshow('Thresholded Image', thresh)
cv2.waitKey(0)
cv2.destroyAllWindows()

4.

# 查找图像边缘整体形成的矩形区域,可能有很多,车牌就在其中一个矩形区域中
contours, hierarchy = cv2.findContours(img_edge2, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

contours, hierarchy = cv2.findContours(image, mode, method[, contours[, hierarchy[, offset]]])

Parameter explanation:

image: input image, usually a binary image (black and white image).
mode: Contour retrieval mode, which defines the hierarchy of contours. Common values ​​are:
cv2.RETR_EXTERNAL: Only detect external contours.
cv2.RETR_LIST: Detect all contours without establishing a hierarchical relationship.
cv2.RETR_CCOMP: Detect all contours and establish a two-level hierarchical relationship.
cv2.RETR_TREE: Detect all contours and build a complete hierarchy.
method: Contour approximation method, used to compress the contour. Common values ​​are:
cv2.CHAIN_APPROX_NONE: store all contour points.
cv2.CHAIN_APPROX_SIMPLE: Store only the endpoints of the contour.
cv2.CHAIN_APPROX_TC89_L1: Use Teh-Chin chain approximation algorithm.
cv2.CHAIN_APPROX_TC89_KCOS: Use Teh-Chin chain approximation algorithm.
contours: Optional parameter, list of detected contours.
hierarchy: optional parameter, outline hierarchy.
return value:

contours: list of detected contours.
hierarchy: Hierarchy of contours, each contour corresponds to four integers [Next, Previous, First_Child, Parent].
This is the content of the value returned by contours.
Please add a picture description

5.

for c in contours:
    x, y, w, h = cv2.boundingRect(c)#这个函数就是用来返回值使用的。

x, y, w, h = cv2.boundingRect(contour)

The function is used to calculate the bounding rectangle of the contour, that is, give the smallest rectangular box enclosing the contour.
Parameter explanation:

contour: The contour of the input.
return value:

x: The x-coordinate of the upper-left point of the bounding rectangle.
y: The y coordinate of the upper left corner of the bounding rectangle.
w: The width of the bounding rectangle.
h: The height of the bounding rectangle.
Use the cv2.boundingRect() function to obtain the boundary rectangle information of the contour, including the coordinates (x, y) of the upper left corner point and the width w and height h of the rectangle. This information can be used for further analysis and processing of contours, such as drawing a bounding rectangle in the image or extracting the image content within the rectangular area. License plate information can be found here.

6.

rect = cv2.minAreaRect(c)

retval, box = cv2.minAreaRect(points)

Used to compute the smallest bounding rectangle for a given set of points. The smallest enclosing rectangle is the rectangle that can completely enclose the set of points and has the smallest area.

Parameter explanation:

points: The set of input points to calculate the minimum bounding rectangle, can be a Numpy array or a Python list containing points.
retval: the return value, indicating the relevant information of the minimum circumscribed rectangle. Normally this return value is not used.
box: The information of the smallest bounding rectangle, returning a tuple of ((center_x, center_y), (width, height), angle), where: (center_x, center_y): the coordinates of the center point of the smallest bounding rectangle
.
(width, height): The width and height of the smallest bounding rectangle.
angle: The rotation angle of the smallest bounding rectangle relative to the horizontal direction.
example

import cv2
import numpy as np

# 定义一个点集
points = np.array([[100, 50], [200, 100], [150, 200], [50, 150]], dtype=np.int32)

# 计算最小外接矩形
retval, box = cv2.minAreaRect(points)

# 提取最小外接矩形的信息
center, size, angle = box
width, height = size

# 在图像上绘制最小外接矩形
rect_points = cv2.boxPoints(box).astype(np.int32)
cv2.drawContours(image, [rect_points], 0, (0, 255, 0), 2)

# 显示图像
cv2.imshow("Image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

7.

area = cv2.contourArea(contour)

Used to calculate the area of ​​a given contour. A contour is a closed curve composed of a series of consecutive points.

Parameter explanation:

contour: The contour to calculate the area, can be a Numpy array containing points.
return value:

area: The area of ​​the contour, in pixels.
the code

import cv2
import numpy as np

# 读取图像并进行灰度化和二值化处理
image = cv2.imread("image.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

# 寻找轮廓
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# 计算轮廓的面积
for contour in contours:
    area = cv2.contourArea(contour)
    print("Contour Area:", area)

# 绘制轮廓
cv2.drawContours(image, contours, -1, (0, 255, 0), 2)

# 显示图像
cv2.imshow("Image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

9.

points = cv2.boxPoints(box)

Parameter explanation:

box: The input rotation rectangle, which can be calculated by the cv2.minAreaRect() function.
return value:

points: The coordinates of the four corners of the rotated rectangle, and a Numpy array containing four coordinate points is returned.
Example usage:

import cv2

# 创建一个旋转矩形
center = (100, 100)
size = (200, 100)
angle = 30
rect = (center, size, angle)

# 计算旋转矩形的四个角点坐标
points = cv2.boxPoints(rect)
print("Points:", points)

# 将浮点型坐标点转换为整数型
points = np.int0(points)

# 绘制旋转矩形
image = np.zeros((200, 200), dtype=np.uint8)
cv2.drawContours(image, [points], 0, 255, 2)

# 显示图像
cv2.imshow("Image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

The input parameter of the cv2.boxPoints() function is a rotated rectangle, which can be calculated by the cv2.minAreaRect() function. The corner coordinates returned by the cv2.boxPoints() function are arranged in a clockwise direction.

10.

cv2.drawContours() and cv2.rectangle() are functions used to draw contours and rectangles in OpenCV. There are the following differences between them:

Draw objects:

cv2.drawContours(image, contours, contourIdx, color, thickness) is used to draw contours, where image is the image on which the contour is to be drawn, contours is a list or array of contours, and contourIdx is the index of the contour to be drawn (-1 means draws all contours), color is the color of the contour, and thickness is the line thickness of the contour.
cv2.rectangle(image, pt1, pt2, color, thickness) is used to draw a rectangle, where image is the image on which to draw the rectangle, pt1 is the coordinates of the upper left corner of the rectangle, pt2 is the coordinates of the lower right corner of the rectangle, and color is the rectangle The color, thickness is the border line width of the rectangle.
scenes to be used:

cv2.drawContours() is suitable for drawing complex contours. It can draw closed and unclosed contours. You can choose to draw a single contour or multiple contours. It is often used for contour detection and analysis.
cv2.rectangle() is suitable for drawing a simple rectangle. The drawn rectangle is a closed quadrilateral, which is often used to mark and locate the target area.
Summary: cv2.drawContours() is used to draw contours, while cv2.rectangle() is used to draw rectangles. The main difference between them is that the drawn objects are different. cv2.drawContours() can draw contours of any shape, while cv2.rectangle() draws rectangles.

Guess you like

Origin blog.csdn.net/guoguozgw/article/details/131393597