1 分割對象
EfficientSAM
https://github.com/yformer/EfficientSAM
2 計算在圖像中最高點即y值最小點
import os
import cv2def read_images(folder_path):image_files = [f for f in os.listdir(folder_path) iff.endswith(".jpg") or f.endswith(".png")] # 獲取文件夾中所有的jpg和png圖片文件sorted_image_files = sorted(image_files, key=lambda x: int(''.join(filter(str.isdigit, os.path.splitext(x)[0]))))images = [] # 用來存儲讀取的圖像for filename in sorted_image_files:# print(filename)image_path = os.path.join(folder_path, filename) # 構建完整的文件路徑image = cv2.imread(image_path) # 使用OpenCV庫讀取圖像文件# image = cv2.resize(image, (0, 0), fx=0.5, fy=0.5, interpolation=cv2.INTER_LINEAR)images.append(image) # 將圖像添加到列表中return imagesdef reprocess_image(img):# 讀入圖片# for i in range(len(images)):# img = images[i]# 顯示圖片# 將彩色圖片轉換成灰度圖像gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)# 二值化處理# ret, thresh = cv2.threshold(gray, 50, 255, 0)# cv2.imshow("Binary Image", thresh)# cv2.waitKey(0)contour_image = img.copy()# 直接用灰度圖尋找輪廓contours, hierarchy = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)# 二值化處理后的圖像再處理輪廓# contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)cv2.drawContours(contour_image, contours, -1, (0, 255, 0), 3)cv2.imshow("contour_image", contour_image)cv2.waitKey(0)return contours, imgdef find_highest_y_point(contours, img):_highest_point = (0, 0)max_y = img.shape[0]for contour in contours:for point in contour:if point[0][1] < max_y:max_y = point[0][1]_highest_point = (point[0][0], point[0][1])# print(highest_point[0])# print(highest_point[1])# 在圖像上標記最高點cv2.circle(img, _highest_point, 5, (0, 0, 255), -1)# 顯示結果cv2.imshow('Highest Point', img)cv2.waitKey(0)cv2.destroyAllWindows()return _highest_pointif __name__ == '__main__':folder_path = "final-images" # 替換為你的文件夾路徑highest_point = (0, 0)real_highest_y = 300if(read_images(folder_path) is not None):print("讀取成功")print(len(read_images(folder_path)))for _image in read_images(folder_path):contours, img = reprocess_image(_image)highest_point = find_highest_y_point(contours, img)real_highest_y = img.shape[0] - highest_point[1]real_highest_y *= 0.25# print("最高點坐標:", highest_point)# print("最高點x坐標:", highest_point[0])# print("最高點y坐標:", highest_point[1])print(real_highest_y)else:print("讀取失敗")
分割后的圖像
結果