Cropping Concave polygon from Image using Opencv python

前端 未结 2 2196
失恋的感觉
失恋的感觉 2020-12-04 20:27

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

and the coordinates of

2条回答
  •  忘掉有多难
    2020-12-04 21:09

    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:

    Result:

提交回复
热议问题