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

2024-04-16 23:42:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我要说的是

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

我想确定这个多边形内像素的颜色,如果它有5个以上的白色像素,那么应该从图像中删除这个多边形

有人能帮我吗。谢谢


Tags: 图像颜色np像素多边形array白色int32
1条回答
网友
1楼 · 发布于 2024-04-16 23:42:35

在Python/OpenCV中有一种方法可以做到这一点但是,我不确定“删除”多边形是什么意思。在下面,我将多边形区域设置为黑色

  • 读取输入
  • 将其转换为灰色
  • 定义多边形顶点
  • 为多边形创建遮罩
  • 从遮罩为255的灰色图像中获取像素颜色
  • 数一数白色的数目
  • 如果计数大于5,则将输入图像中的多边形区域设置为黑色;否则就别管它了
  • 保存结果

输入:

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

相关问题 更多 >