用Python和OpenCV对图片进行二值化,腐蚀,膨胀,去除小面积区域,定位大面积区域,最后分别返回他们的图片结果的代码
时间: 2024-04-29 07:21:14 浏览: 11
以下是用Python和OpenCV对图片进行二值化,腐蚀,膨胀,去除小面积区域,定位大面积区域,最后分别返回他们的图片结果的代码:
``` python
import cv2
import numpy as np
def binary_image(image):
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
return binary
def erode_image(image, kernel_size=3):
kernel = np.ones((kernel_size, kernel_size), np.uint8)
eroded = cv2.erode(image, kernel, iterations=1)
return eroded
def dilate_image(image, kernel_size=3):
kernel = np.ones((kernel_size, kernel_size), np.uint8)
dilated = cv2.dilate(image, kernel, iterations=1)
return dilated
def remove_small_area(image, min_area=100):
contours, hierarchy = cv2.findContours(image, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
for index, contour in enumerate(contours):
area = cv2.contourArea(contour)
if area < min_area:
cv2.drawContours(image, [contour], -1, (0, 0, 0), -1)
return image
def locate_big_area(image, min_area=1000):
contours, hierarchy = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
max_area = 0
max_contour = None
for index, contour in enumerate(contours):
area = cv2.contourArea(contour)
if area > min_area and area > max_area:
max_area = area
max_contour = contour
if max_contour is None:
return None
rect = cv2.minAreaRect(max_contour)
box = np.int0(cv2.boxPoints(rect))
cv2.drawContours(image, [box], 0, (0, 0, 255), 2)
return image
if __name__ == '__main__':
image = cv2.imread('example.jpg')
binary = binary_image(image)
cv2.imshow('binary', binary)
eroded = erode_image(binary)
cv2.imshow('eroded', eroded)
dilated = dilate_image(binary)
cv2.imshow('dilated', dilated)
removed = remove_small_area(binary)
cv2.imshow('removed', removed)
located = locate_big_area(binary)
cv2.imshow('located', located)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在这里,我们定义了五个函数,分别是`binary_image`、`erode_image`、`dilate_image`、`remove_small_area`和`locate_big_area`。
`binary_image`函数将原始图像转换为二值图像。
`erode_image`函数将二值图像进行腐蚀操作。
`dilate_image`函数将二值图像进行膨胀操作。
`remove_small_area`函数将二值图像中小于指定面积的区域去除。
`locate_big_area`函数定位二值图像中面积最大的区域。
在主函数中,我们读取一张示例图片,并分别对其进行二值化、腐蚀、膨胀、去除小面积区域和定位大面积区域的操作,并将结果显示在窗口中。