gpt4 book ai didi

python - 使用 Opencv python 从图像中裁剪凹多边形

转载 作者:太空狗 更新时间:2023-10-30 00:22:41 24 4
gpt4 key购买 nike

如何从图像中裁剪凹多边形。我的输入图像看起来像 this .

闭合多边形的坐标是[10,150]、[150,100]、[300,150]、[350,100]、[310,20]、[35,10]。我希望使用 opencv 裁剪由凹多边形包围的区域。我搜索了其他类似的问题,但找不到正确的答案。这就是我问的原因?你能帮帮我吗。

任何帮助将不胜感激。!!!

最佳答案

Steps

  1. find region using the poly points
  2. create mask using the poly points
  3. do mask op to crop
  4. add white bg if needed

代码:

# 2018.01.17 20:39:17 CST
# 2018.01.17 20:50:35 CST
import numpy as np
import cv2

img = cv2.imread("test.png")
pts = np.array([[10,150],[150,100],[300,150],[350,100],[310,20],[35,10]])

## (1) Crop the bounding rect
rect = cv2.boundingRect(pts)
x,y,w,h = rect
croped = img[y:y+h, x:x+w].copy()

## (2) make mask
pts = pts - pts.min(axis=0)

mask = np.zeros(croped.shape[:2], np.uint8)
cv2.drawContours(mask, [pts], -1, (255, 255, 255), -1, cv2.LINE_AA)

## (3) do bit-op
dst = cv2.bitwise_and(croped, croped, mask=mask)

## (4) add the white background
bg = np.ones_like(croped, np.uint8)*255
cv2.bitwise_not(bg,bg, mask=mask)
dst2 = bg+ dst


cv2.imwrite("croped.png", croped)
cv2.imwrite("mask.png", mask)
cv2.imwrite("dst.png", dst)
cv2.imwrite("dst2.png", dst2)

源图片:

enter image description here

结果:

enter image description here

关于python - 使用 Opencv python 从图像中裁剪凹多边形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48301186/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com