【问题标题】:Detecting a rectangle and cropping the image to its size检测矩形并将图像裁剪为其大小
【发布时间】:2017-07-30 17:29:09
【问题描述】:

我是图像处理的新手,开始学习 scikit-image。我正在尝试检测矩形的角,然后将整个图像裁剪到它。但是我迷失在大量的分割和检测算法中,不知道我需要哪一种以及如何去做。

此代码生成示例图像。我想将它裁剪为绿色矩形。我需要做什么?

从 matplotlib 导入 pyplot 作为 pyplot

import numpy as np
import skimage
from skimage import draw

img = np.zeros((500, 500, 3), dtype=np.double)

poly = np.array([[25, 25],
                 [25, 75],
                 [75, 75],
                 [75, 25]])

rr, cc = draw.polygon(poly[:, 0], poly[:, 1], img.shape)

img[rr, cc, 1] = 1
plt.imshow(img)
plt.show()

任务是检测矩形(多边形阵列)的边缘并将图像裁剪到它。

我尝试了 harris 角点检测、canny 边缘检测和许多其他方法,但我完全糊涂了。这似乎是一项简单的任务,但我不明白。

使用 OpenCV 会更容易吗?请帮忙!

【问题讨论】:

标签: python image-processing edge-detection scikit-image


【解决方案1】:

如果您依赖于轮廓查找方法,OpenCV 是目前最好的选择。如果您可以通过其他方式识别对象,则 skimage 可以很容易地识别坐标并裁剪图像。例如:

import numpy as np
import skimage
from skimage import draw, measure
import matplotlib.pyplot as plt

# --- Generate test data ---
img = np.zeros((500, 500, 3), dtype=np.double)

poly = np.array([[25, 25],
                 [25, 75],
                 [75, 75],
                 [75, 25]])

rr, cc = draw.polygon(poly[:, 0], poly[:, 1], img.shape)

img[rr, cc, 1] = 1
# --- End generate test data ---

# Generate a mask with all objects close to green
green = (0, 1, 0)
mask = np.sum((img - green)**2, axis=2) < 0.1

# Label the different objects in the image
label_img = measure.label(mask)

# Find all objects
regions = measure.regionprops(label_img)

# Find the first object (since we only have one, that's the rectangle!)
r = regions[0]

# We'll use the `bbox` property to select the bounding box
# # For a full list of properties, take a look at the docstring of
# measure.regionprops

print('The bounding box is {}'.format(r.bbox))

r0, c0, r1, c1 = r.bbox
img_crop = img[r0:r1, c0:c1]

f, (ax0, ax1) = plt.subplots(1, 2)
ax0.imshow(img)
ax1.imshow(img_crop)
plt.show()

【讨论】:

  • 谢谢!你能再帮帮我吗?您的解决方案适用于该示例,但我的实际图片出现错误。当试图生成掩码时,我得到一个 numpy 错误,因为矩阵不兼容:ValueError: operands could not be broadcast together with shapes (2048,2456) (3,)。我真的不明白,因为图像数组应该具有与示例相同的尺寸(仅具有更多像素)
猜你喜欢
  • 2018-01-27
  • 2016-07-18
  • 1970-01-01
  • 2012-02-11
  • 2020-07-02
  • 2021-09-07
  • 2019-06-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多