-
cv2.boundingRect傳回的是左上角坐标和寬高(x1, y1, w, h)
import cv2
import numpy as np
img_path = "./1.png"
img = cv2.imdecode(np.fromfile(img_path, dtype=np.uint8), 1)
# 1.灰階化
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 2.二值化
_, bi_image = cv2.threshold(img_gray, 150, 255, cv2.THRESH_BINARY)
# 3.結構化
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (30, 30))
# bi_image = cv2.morphologyEx(bi_image, cv2.MORPH_OPEN, kernel)
bi_image = cv2.erode(bi_image, kernel, iterations=1)
# 4.尋找輪廓
counts, _ = cv2.findContours(bi_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
colors_list = [(0,0,255), (0, 255,0),(255,0,0)]
for i, j in enumerate(counts):
area = cv2.contourArea(j)
if 200000 > area > 100000:
rect = cv2.boundingRect(j)
x_min, y_min, w, h = rect
x_max, y_max = x_min+w, y_min+h
cv2.rectangle(img, (int(x_min), int(y_min)), (int(x_min+w), int(y_min+h)), colors_list[i], thickness=2)
new_img = img[y_min:y_max, x_min:x_max]
cv2.imshow("i", img)
# cv2.imshow("img", new_img)
cv2.waitKey()
2. cv2.minAreaRect傳回的坐标是:(中心點坐标),(寬,高),旋轉角度
import cv2
import os
import numpy as np
import time
folder_path = r'' # 圖檔所在的檔案夾路徑
t1 =time.time()
for i in os.listdir(folder_path):
image_path = os.path.join(folder_path, i)
ori_image = cv2.imdecode(np.fromfile(image_path, dtype=np.uint8), 1)
gray_image = cv2.cvtColor(ori_image, cv2.COLOR_BGR2GRAY)
_, bi_image = cv2.threshold(gray_image, 50, 255, cv2.THRESH_BINARY)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (21, 21))
bi_image = cv2.dilate(bi_image, kernel)
counts, _ = cv2.findContours(bi_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
x, y, w, h, t = 0,0,0,0,90
for j in counts:
area = cv2.contourArea(j)
if 1000000 > area > 700000: # 設定的過濾面積
rect = cv2.minAreaRect(j)
(x, y), (w, h), t = rect
points_rect = cv2.boxPoints(rect) # 中心(x,y) 寬高(w,h) 旋轉角度
box = np.int0(points_rect)
ori_image = cv2.drawContours(ori_image, [box], 0, (0, 0, 255), 2)