You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在OpenCV中依据指定角点裁剪图像并修正检测问题

问题描述

需要找到图像中最靠近左下角和右上角的非黑色像素点A、B,以此裁剪图像去除周围黑边:

  • 输入图像1:
    输入图像1
  • 期望输出:
    期望输出
当前错误代码

以下代码无法正确定位目标像素点:

def CheckForLess(list1, val):
    return(all(x < val for x in list1))

def find_corner_pixels(img):
    # Get image dimensions
    height, width = img.shape[:2]

    # Find the first non-black pixel closest to the left-down and right-up corners
    nonempty = []

    for i in range(height):
        for j in range(width):
            # Check if the current pixel is non-black
            if not CheckForLess(img[i, j], 10):
                nonempty.append([i, 1080 - j])

    return min(nonempty) , max(nonempty)
现有方案局限性

某解决方案在上述图像中有效,但更换为以下输入图像时:
输入图像2
输出结果错误:
错误输出

修正后的解决方案

通过精准提取所有非黑像素的边界,实现稳定的图像裁剪:

import numpy as np
import cv2

def find_crop_bounds(img):
    # 兼容彩色/灰度图,转为灰度图判断非黑区域
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) if len(img.shape) == 3 else img
    
    # 获取所有非黑像素的坐标(阈值与原逻辑一致,设为10)
    non_black_coords = np.where(gray >= 10)
    
    # 提取边界坐标
    y_min = np.min(non_black_coords[0])
    y_max = np.max(non_black_coords[0])
    x_min = np.min(non_black_coords[1])
    x_max = np.max(non_black_coords[1])
    
    # 返回裁剪范围(切片左闭右开,需+1确保包含边界像素)
    return (y_min, y_max + 1), (x_min, x_max + 1)

def crop_image(img):
    (y_start, y_end), (x_start, x_end) = find_crop_bounds(img)
    return img[y_start:y_end, x_start:x_end]

# 使用示例
if __name__ == "__main__":
    input_img = cv2.imread("your_input_image.png")
    cropped_img = crop_image(input_img)
    cv2.imwrite("cropped_result.png", cropped_img)

关键说明:

  • 避免硬编码坐标(如原代码中的1080-j),适配任意尺寸图像
  • 用numpy.where高效获取所有非黑像素,比双重循环更高效准确
  • 直接取所有非黑像素的极值坐标,确保裁剪出包含有效内容的最小区域

内容的提问来源于stack exchange,提问作者vojtam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 23:40:34