最新推送
This commit is contained in:
46
muban/choose-roi.py
Normal file
46
muban/choose-roi.py
Normal file
@ -0,0 +1,46 @@
|
||||
import cv2
|
||||
import os
|
||||
|
||||
def select_and_output_roi(img_path, save=True, save_dir="roi_output"):
|
||||
img = cv2.imread(img_path)
|
||||
if img is None:
|
||||
raise RuntimeError("无法读取图片")
|
||||
|
||||
# OpenCV 自带 ROI 选择工具
|
||||
roi = cv2.selectROI(
|
||||
windowName="Select ROI (ENTER or C to confirm, ESC to quit)",
|
||||
img=img,
|
||||
showCrosshair=True,
|
||||
fromCenter=False
|
||||
)
|
||||
|
||||
cv2.destroyAllWindows()
|
||||
|
||||
x, y, w, h = roi
|
||||
print(f"[INFO] ROI = (x={x}, y={y}, w={w}, h={h})")
|
||||
|
||||
roi_img = img[y:y+h, x:x+w]
|
||||
|
||||
if save:
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
save_path = os.path.join(save_dir, "roi.png")
|
||||
cv2.imwrite(save_path, roi_img)
|
||||
print(f"[INFO] ROI 图像已保存: {save_path}")
|
||||
|
||||
return roi, roi_img
|
||||
|
||||
|
||||
# ----------------------------
|
||||
# main 测试
|
||||
# ----------------------------
|
||||
if __name__ == "__main__":
|
||||
IMAGE_PATH = "test2.png" # 换成你的图片
|
||||
|
||||
roi, roi_img = select_and_output_roi(
|
||||
IMAGE_PATH,
|
||||
save=True
|
||||
)
|
||||
|
||||
cv2.imshow("ROI Result", roi_img)
|
||||
cv2.waitKey(0)
|
||||
cv2.destroyAllWindows()
|
||||
Reference in New Issue
Block a user