【问题标题】:Crop Image from all sides after edge detection边缘检测后从四面八方裁剪图像
【发布时间】:2016-03-04 01:47:44
【问题描述】:

我是 OpenCV 的新手。我想从图像中提取主要对象。因此,我在图像上应用了 Canny 以获取主要对象周围的边缘并得到以下输出:

以下是在 Python 中使用 OpenCV 获得此功能的代码:

img = cv2.imread(file)
cv2.imshow("orig", img)
cv2.waitKey(0)
img = cv2.blur(img,(2,2))
gray_seg = cv2.Canny(img, 0, 50)

现在,我想在仅获取图像中的主要对象后将下图作为最终输出:

我想以优化的方式来做,因为我必须处理超过 250 万张图像。 谁能帮我解决这个问题?

【问题讨论】:

  • 我想你的精明会给你一个数量级的矩阵。只需设置一个阈值,然后找到最左侧、最右侧、最顶部和最底部的像素越过阈值,然后沿着穿过找到点的垂直和水平线切割。
  • 250 万 = 250 万?
  • 您是否需要使用 OpenCV 来完成此操作,还是 ImageJ 脚本也可以?
  • @JanEglinger 这必须使用 OpenCV 完成
  • 只需获取边缘掩码的boundingRect,并相应地对图像进行切片。

标签: python image opencv image-processing


【解决方案1】:

既然你已经找到clean canny edge,那么要裁剪矩形区域,你应该计算rectangle boundary

步骤:

结果:


要计算 canny 区域边界,您只需找到非零点,然后获取 min-max coords。使用 NumPy 很容易实现。然后使用 slice-op 进行裁剪。

#!/usr/bin/python3
# 2018.01.20 15:18:36 CST

#!/usr/bin/python3
# 2018.01.20 15:18:36 CST

import cv2
import numpy as np
#img = cv2.imread("test.png")
img = cv2.imread("img02.png")
blurred = cv2.blur(img, (3,3))
canny = cv2.Canny(blurred, 50, 200)

## find the non-zero min-max coords of canny
pts = np.argwhere(canny>0)
y1,x1 = pts.min(axis=0)
y2,x2 = pts.max(axis=0)

## crop the region
cropped = img[y1:y2, x1:x2]
cv2.imwrite("cropped.png", cropped)

tagged = cv2.rectangle(img.copy(), (x1,y1), (x2,y2), (0,255,0), 3, cv2.LINE_AA)
cv2.imshow("tagged", tagged)
cv2.waitKey()

当然,在积分上做boundingRect也可以。

【讨论】:

    【解决方案2】:

    rect 函数应该提供您需要的功能。如何使用它的示例如下所示。

    cv::Mat image(img);
    cv::Rect myROI(posX, posY, sizeX, sizeY);   
    cv::Mat croppedImage = image(myROI);
    

    这是用 c++ 编写的,但应该能够找到对应的 python。

    我下面的链接提供更多信息 How to crop a CvMat in OpenCV?

    【讨论】:

    • 请注意,您需要将图像转换为矩阵才能使用此功能
    猜你喜欢
    • 2020-07-09
    • 2017-11-07
    • 2015-07-29
    • 1970-01-01
    • 2019-02-09
    • 2012-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多