使用 Opencv python 从图像中裁剪凹多边形 [英] Cropping Concave polygon from Image using Opencv python

查看:65
本文介绍了使用 Opencv python 从图像中裁剪凹多边形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I crop a concave polygon from an image. My Input image look like .

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

and the coordinates of closed polygon are [10,150],[150,100],[300,150],[350,100],[310,20],[35,10]. I want region bounded by concave polygon to be cropped using opencv. I searched for other similar questions but I did not able to find correct answer. That's why I am asking it ? Can you help me.

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

Any help would be highly appreciated.!!!

推荐答案

步骤

  1. 使用多边形查找区域
  2. 使用多边形创建蒙版
  3. 做遮罩操作来裁剪
  4. 如果需要,添加白色背景

代码:

# 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)


源图像:


Source image:

结果:

这篇关于使用 Opencv python 从图像中裁剪凹多边形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆