将图像分成两个相等的部分python opencv

新手上路,请多包涵

有人能告诉我如何将图像分成上下两部分吗?这样我就可以重叠它们。例如,我有一个图像,我应该将它划分以计算每个部分的像素数。我是 OpenCV 的新手,并不完全了解图像的几何形状。

原文由 AinurZhappass 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 490
2 个回答

您可以水平裁剪图像的顶部和底部。

打开图像。

 import cv2
import numpy as np
image = cv2.imread('images/blobs1.png')
cv2.imshow("Original Image", image)
cv2.waitKey(0)

使用 image.shape 让我们捕获高度和宽度变量。

 height, width = image.shape[:2]
print image.shape

现在我们可以开始裁剪了。

 # Let's get the starting pixel coordiantes (top left of cropped top)
start_row, start_col = int(0), int(0)
# Let's get the ending pixel coordinates (bottom right of cropped top)
end_row, end_col = int(height * .5), int(width)
cropped_top = image[start_row:end_row , start_col:end_col]
print start_row, end_row
print start_col, end_col

cv2.imshow("Cropped Top", cropped_top)
cv2.waitKey(0)
cv2.destroyAllWindows()

# Let's get the starting pixel coordiantes (top left of cropped bottom)
start_row, start_col = int(height * .5), int(0)
# Let's get the ending pixel coordinates (bottom right of cropped bottom)
end_row, end_col = int(height), int(width)
cropped_bot = image[start_row:end_row , start_col:end_col]
print start_row, end_row
print start_col, end_col

cv2.imshow("Cropped Bot", cropped_bot)
cv2.waitKey(0)
cv2.destroyAllWindows()

最后,我们可以使用 image.size 给出每个部分的像素数。

 cropped_top.size
cropped_bot.size

你可以用轮廓做同样的事情,但它会涉及边界框。

原文由 avereux 发布,翻译遵循 CC BY-SA 3.0 许可协议

为了简化@avereux 的回答:

在 Python 中,您可以使用拼接将图像分解为子图像。语法是:

 sub_image = full_image[y_start: y_end, x_start:x_end]

请注意,对于图像,原点是图像的左上角。因此,图像第一行(即最上面的一行)上的像素的坐标为 x_coordinate = x, y_coordinate = 0

要获取图像的形状,请使用 image.shape 。这将返回 (no_of_rows, no_of_cols)

您可以使用它们以任何您想要的方式分解图像。

原文由 Shawn Mathew 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题