Cropping Concave polygon from Image using Opencv python

Himanshu Tiwari picture Himanshu Tiwari · Jan 17, 2018 · Viewed 14.8k times · Source

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

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.!!!

Answer

Kinght 金 picture Kinght 金 · Jan 17, 2018

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

The code:

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

enter image description here

Result:

enter image description here