调用原生opencv ROI 手动切割图片区域

本文将介绍如何使用Python和OpenCV库开发一个简单的工具,该工具可以自动识别并切割图片,以便进一步的分析和评分。

用法十分简单,启动程序后,鼠标选定区域,绘制切割的矩形后,按下space键,执行完一次切割操作,循坏往复。按esc键退出。

以下是代码合集:

import cv2
import time
import os

class CutImgManual:
    """
    识别答题卡答题区域工具类
    """
    def __init__(self, path):
        """
        @param path: 待处理答题卡图片路径
        """
        self.img_data = cv2.imread(path, 0)
        if self.img_data is None:
            raise ValueError("图像加载失败,请检查路径或文件格式")
        self.roi_rects = []  # 存储用户选择的ROI

    def save(self, output_dir, debug_dir):
        """
        保存答题区域并标记轮廓
        @param output_dir: 保存的目录
        @param debug_dir: 调试图片保存目录
        @return: None
        """
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)
        if not os.path.exists(debug_dir):
            os.makedirs(debug_dir)
        # 创建一个彩色图像用于绘制轮廓
        color_img = cv2.cvtColor(self.img_data, cv2.COLOR_GRAY2BGR)
        # 交互式选择ROI
        self.select_roi(color_img)
        for idx, rect in enumerate(self.roi_rects):
            x, y, w, h = rect
            ROI = self.img_data[y:y + h, x:x + w]
            # 保存图像
            output_path = os.path.join(output_dir, f"detected_section_{idx}.png")
            cv2.imwrite(output_path, ROI )
            print(f"保存切割并矫正后的图片为: {output_path}")

    def correct_image(self, image):
        """
        矫正图像
        @param image: 待矫正的图像
        @return: 矫正后的图像
        """
        height, width = image.shape
        new_width = int(width * 1.025)
        new_height = int(height * 1.025)
        corrected_image = cv2.resize(image, (new_width, new_height), interpolation=cv2.INTER_LINEAR)
        return corrected_image

    def select_roi(self, image):
        """
        交互式选择ROI
        @param image: 待选择ROI的图像
        @return: None
        """
        rois = cv2.selectROIs("Select ROIs", image)
        for roi in rois:
            x, y, w, h = roi
            self.roi_rects.append((x, y, w, h))
        cv2.destroyAllWindows()

if __name__ == '__main__':
    s = time.time()
    image_path = r"切割路径"
    output_dir = r"输出路径"
    debug_dir = r"调试"  # 
    try:
        c = CutImgManual(image_path)
        c.save(output_dir, debug_dir)
    except ValueError as e:
        print(e)
    print("处理时间:", time.time() - s)

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值