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

基于网格定位含黑像素的右上角区域并实现自动裁剪

修改OpenCV代码实现右上角区域自动裁剪

要实现右上角区域的自动裁剪,核心是调整目标网格的定位逻辑和裁剪区域的坐标计算,具体修改如下:

关键修改点

  1. 定位右上角网格:原代码找的是所有含黑像素网格中行最小、列最小的左上角块,现在需要找**行最小(最顶部)、列最大(最右侧)**的右上角块。
  2. 调整裁剪坐标:针对右上角的目标网格,需要向左扩展crop_size个网格宽度,向下扩展crop_size个网格高度,确保覆盖页码区域。

修改后的完整代码

import cv2
import numpy as np

# 加载灰度图
image = cv2.imread('input.jpg', cv2.IMREAD_GRAYSCALE)

# 获取图像尺寸
h, w = image.shape

# 定义网格行列数
rows = 30
cols = 40

# 计算每个网格的像素尺寸
square_h = h // rows
square_w = w // cols

# 创建网格标记数组
grid = np.zeros((rows, cols), dtype=int)

# 遍历网格,标记含黑像素的网格为1
for i in range(rows):
    for j in range(cols):
        x = j * square_w
        y = i * square_h
        square = image[y:y+square_h, x:x+square_w]
        if np.any(square < 255):
            grid[i, j] = 1

# 定位右上角含黑像素的网格
non_zero_grids = np.argwhere(grid == 1)
# 筛选最顶部的所有网格
top_row_grids = non_zero_grids[non_zero_grids[:, 0] == non_zero_grids[:, 0].min()]
# 在顶部网格中取最右侧的列
top_right_grid = top_row_grids[top_row_grids[:, 1].argmax()]

row, col = top_right_grid

# 定义裁剪的网格范围
crop_size = 3

# 计算裁剪区域坐标(防止超出图像边界)
x_start = max((col - crop_size + 1) * square_w, 0)
y_start = row * square_h
x_end = (col + 1) * square_w
y_end = min((row + crop_size) * square_h, h)

# 裁剪图像
cropped_image = image[y_start:y_end, x_start:x_end]

# 保存结果
cv2.imwrite('output.jpg', cropped_image)

代码说明

  • 定位逻辑优化:先提取所有含黑像素的网格坐标,筛选出最顶部的行后,再取其中列索引最大的网格,精准锁定右上角目标区域。
  • 边界处理:用max()和min()限制裁剪坐标范围,避免因crop_size过大导致超出图像边界。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 10:07:40