cv2-多邊形填充


多邊形圖像填充

cv2.fillPoly

cv2.fillPoly(img, pts, color,lineType=None,shift=None,offset=None)

用來填充任意形狀的圖像,常常用於多邊形的填充,可用於一個或者多個圖形的填充

參數說明

  • img 圖片
  • pts 多邊形坐標 array類型,最好帶上[]
  • color填充顏色
area1 = np.array([[250, 200], [300, 100], [750, 800], [100, 1000]])
area2 = np.array([[1000, 200], [1500, 200], [1500, 400], [1000, 400]])

img = np.zeros((1080, 1920, 3), np.uint8)

cv2.fillPoly(img,[area1,area2], color=(255, 255, 255))
plt.imshow(img)
plt.show()

img

cv2.fillConvexPoly

可用於對一個圖像的填充,只能用來填充凸多邊形

cv2.fillConvexPoly(img, points, color)

  • img Image.
  • points Polygon vertices.
  • color Polygon color.
  • lineType Type of the polygon boundaries.

單個多邊形填充。

img = np.zeros((1080, 1920, 3), np.uint8)
triangle = np.array([[0, 0], [1500, 800], [500, 400]])
     
cv2.fillConvexPoly(img, triangle, (255, 255, 255))
     
plt.imshow(img)
plt.show()
img

作用

制作掩膜,實現任意區域裁剪

 # 加載圖像
img = cv2.imread("D:\\shi\\a.png") 

# 坐標點points
pts = np.array([[(200, 200), (1800, 100), (1600, 800), (200, 800), (100, 400)]], dtype=np.int32)

# 作為mask
mask = np.zeros(img.shape[:2], np.uint8)  # 全0

# 在mask上將多邊形區域填充為白色
cv2.fillPoly(mask, pts, 255)  # 填充,用 255 填充

# 通過 mask 來提取  mask 對應 原圖像的索引
img_height = mask.shape[0]
img_weight = mask.shape[1]

# 逐位與,得到裁剪后圖像,此時是黑色背景
dst = cv2.bitwise_and(img, img, mask=mask)
    
bg = np.ones_like(img, np.uint8) * 255
bg = cv2.bitwise_not(bg, bg, mask=mask)  # bg的多邊形區域為0,背景區域為255
dst_white = bg + dst

# 添加其他顏色背景
other = np.ones_like(img) * 128  # 其他背景顏色
mask2 = np.ones(img.shape, np.uint8) * 255
mask2 = cv2.fillPoly(mask2, [pts], (0, 0, 0,))
other = cv2.bitwise_and(other, mask2)
dst_other = dst + other

cv2.imwrite("dst-mask.jpg", mask)
cv2.imwrite("dst-black.jpg", dst)
cv2.imwrite("dst-white.jpg", dst_white)
cv2.imwrite("other-otherd.jpg", dst_other)

按位運算

  • bitwise_and 是對二進制數據進行“與”操作,即對圖像每個像素值進行二進制“與”操作,1&1=1,1&0=0,0&1=0,0&0=0

  • bitwise_or是對二進制數據進行“或”操作,即對圖像每個像素值進行二進制“或”操作,1|1=1,1|0=0,0|1=0,0|0=0

  • bitwise_xor是對二進制數據進行“異或”操作,即對圖像每個像素值進行二進制“異或”操作,1^1=0,1^0=1,0^1=1,0^0=0

  • bitwise_not是對二進制數據進行“非”操作,即對圖像每個像素值進行二進制“非”操作,~1=0,~0=1

參考文獻: https://www.pianshen.com/article/5724129910/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM