Cropping Concave polygon from Image using Opencv python

前端 未结 2 2188
失恋的感觉
失恋的感觉 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-04 21:07

    You can do it in 3 steps:

    1. Create a mask out of the image

      mask = np.zeros((height, width)) points = np.array([[[10,150],[150,100],[300,150],[350,100],[310,20],[35,10]]]) cv2.fillPoly(mask, points, (255))

    2. Apply mask to original image

      res = cv2.bitwise_and(img,img,mask = mask)

    3. Optionally you can remove the crop the image to have a smaller one

      rect = cv2.boundingRect(points) # returns (x,y,w,h) of the rect cropped = res[rect[1]: rect[1] + rect[3], rect[0]: rect[0] + rect[2]]

    With this you should have at the end the image cropped

    UPDATE

    For the sake of completeness here is the complete code:

    import numpy as np
    import cv2
    
    img = cv2.imread("test.png")
    height = img.shape[0]
    width = img.shape[1]
    
    mask = np.zeros((height, width), dtype=np.uint8)
    points = np.array([[[10,150],[150,100],[300,150],[350,100],[310,20],[35,10]]])
    cv2.fillPoly(mask, points, (255))
    
    res = cv2.bitwise_and(img,img,mask = mask)
    
    rect = cv2.boundingRect(points) # returns (x,y,w,h) of the rect
    cropped = res[rect[1]: rect[1] + rect[3], rect[0]: rect[0] + rect[2]]
    
    cv2.imshow("cropped" , cropped )
    cv2.imshow("same size" , res)
    cv2.waitKey(0)
    

    For the colored background version use the code like this:

    import numpy as np
    import cv2
    
    img = cv2.imread("test.png")
    height = img.shape[0]
    width = img.shape[1]
    
    mask = np.zeros((height, width), dtype=np.uint8)
    points = np.array([[[10,150],[150,100],[300,150],[350,100],[310,20],[35,10]]])
    cv2.fillPoly(mask, points, (255))
    
    res = cv2.bitwise_and(img,img,mask = mask)
    
    rect = cv2.boundingRect(points) # returns (x,y,w,h) of the rect
    im2 = np.full((res.shape[0], res.shape[1], 3), (0, 255, 0), dtype=np.uint8 ) # you can also use other colors or simply load another image of the same size
    maskInv = cv2.bitwise_not(mask)
    colorCrop = cv2.bitwise_or(im2,im2,mask = maskInv)
    finalIm = res + colorCrop
    cropped = finalIm[rect[1]: rect[1] + rect[3], rect[0]: rect[0] + rect[2]]
    
    cv2.imshow("cropped" , cropped )
    cv2.imshow("same size" , res)
    cv2.waitKey(0)
    

提交回复
热议问题