【问题标题】:poly crop image python: How to change mask color多边形裁剪图像python:如何更改蒙版颜色
【发布时间】:2020-09-15 18:36:26
【问题描述】:

我正在使用多边形数组裁剪图像,但我需要将 swoed 蒙版颜色更改为 PINK,以便另一个程序将其识别为蒙版。该怎么做?

    import numpy as np
    import cv2
    import time
    
    img = cv2.imread("teste3.jpg")
    start=time.time()
    height = img.shape[0]
    width = img.shape[1]
    
    mask = np.zeros((height, width), dtype=np.uint8)
    points = np.array([[[692,71],[1386,71],[1617,520],[1617,817],[495,817],[692,520]]])
    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]]
    print(time.time() - start)
    cv2.imshow("cropped" , cropped )
    cv2.waitKey(0)

【问题讨论】:

    标签: python opencv polygon mask


    【解决方案1】:

    有几种方法:

    • numpy 条件表达式(在 35 毫秒内完成):

      pink = (255, 0, 255)
      res = img.copy()
      res[mask==0] = pink
      
    • cv2 split+bitwises+merge(20 毫秒内完成):

      pink = (255, 0, 255)
      whitesheet = np.full_like(mask, 255)
      mask_inv = cv2.bitwise_not(mask)
      channels = cv2.split(img)
      for i in range(len(channels)):
          a = cv2.bitwise_and(whitesheet, channels[i], mask=mask)
          b = cv2.bitwise_and(whitesheet, pink[i], mask=mask_inv)
          channels[i] = cv2.bitwise_or(a, b)
      res = cv2.merge(channels)
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-03
      • 2021-11-01
      • 1970-01-01
      • 2020-11-03
      • 1970-01-01
      • 1970-01-01
      • 2012-12-10
      • 2019-11-01
      相关资源
      最近更新 更多