如何使用python检查多边形内像素的颜色并删除包含白色像素的多边形?

时间:2020-04-01 05:30:16

标签: python opencv image-processing

我有一个多边形,

polyg = np.array([[[247,358],[247,361],[260,361],[268,362],[288,363],[303,365],[314,365],[315,364],[247,358]]],np.int32) 

我想确定此多边形内像素的颜色,如果它的白色像素超过5个,则应从图像中删除该多边形。

谁能帮助我。谢谢!

1 个答案:

答案 0 :(得分:2)

这是在Python / OpenCV中执行此操作的一种方法。 但是,我不确定“删除”多边形是什么意思。在下面,我将多边形区域设为黑色。

  • 阅读输入内容
  • 将其转换为灰色
  • 定义多边形顶点
  • 为多边形创建蒙版
  • 从蒙版为255的灰色图像中获取像素颜色
  • 计算白色的数量
  • 如果计数大于5,则使输入图像中的多边形区域为黑色;否则,为0。否则就别管它了
  • 保存结果

输入:

enter image description here

import cv2
import numpy as np

# read image
img = cv2.imread('barn.png')

# convert image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# define polygon points
points = np.array( [[[200,0],[230,0],[230,30],[200,30]]], dtype=np.int32 )

# draw polygon on input to visualize
img_poly = img.copy()
cv2.polylines(img_poly, [points], True, (0,0,255), 1)

# create mask for polygon
mask = np.zeros_like(gray)
cv2.fillPoly(mask,[points],(255))

# get color values in gray image corresponding to where mask is white
values = gray[np.where(mask == 255)]

# count number of white values
count = 0
for value in values:
    if value == 255:
        count = count + 1
print("count =",count)

if count > 5:
    result = img.copy()
    result[mask==255] = (0,0,0)
else:
    result = img


# save results
cv2.imwrite('barn_polygon.png', img_poly)
cv2.imwrite('barn_mask.png', mask)
cv2.imwrite('barn_poly_result.png', result)

cv2.imshow('barn_poly', img_poly)
cv2.imshow('barn_mask', mask)
cv2.imshow('barn_result', result)
cv2.waitKey()


输入显示红色多边形(仅一个正方形):

enter image description here

面具:

enter image description here

报告数量:

count = 36


生成的多边形变黑的图像:

enter image description here