Skip to content

Instantly share code, notes, and snippets.

@z4none
Created November 22, 2023 04:31
Show Gist options
  • Save z4none/f9f8bcc4a71ff5316418b23fccae18ad to your computer and use it in GitHub Desktop.
Save z4none/f9f8bcc4a71ff5316418b23fccae18ad to your computer and use it in GitHub Desktop.
image process
import cv2
import numpy as np
def preprocess_image(image):
# 二值化
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, threshold = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
cv2.imwrite("01_threshold.jpg", threshold)
return threshold
def process_image(image):
# 腐蚀膨胀
kernel = np.ones((10,10), np.uint8)
eroded = cv2.erode(image, kernel, iterations=1)
dilated = cv2.dilate(eroded, kernel, iterations=1)
cv2.imwrite("02_eroded_dilated.jpg", dilated)
return dilated
def remove_small_regions(image):
# 消除小块区域
contours, _ = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
area = cv2.contourArea(contour)
if area < 500: # 设定阈值,根据实际情况调整
cv2.drawContours(image, [contour], -1, 0, -1)
cv2.imwrite("03_removed_small_regions.jpg", image)
return image
def find_min_enclosing_rectangle(image):
# 找出最小外接矩形
contours, _ = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
rect = cv2.minAreaRect(contour)
box = cv2.boxPoints(rect)
box = np.intp(box)
print(box)
image1 = cv2.drawContours(image, [box], 0, 255, 2)
cv2.imwrite("04_min_enclosing_rectangle.jpg", image1)
# 读取输入图像
image = cv2.imread("1.png")
# 预处理图像
threshold_image = preprocess_image(image)
# 进行腐蚀膨胀操作
processed_image = process_image(threshold_image)
# 消除小块区域
removed_regions_image = remove_small_regions(processed_image)
# 找出最小外接矩形
find_min_enclosing_rectangle(removed_regions_image)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment