查找尺寸小于 x 的特定颜色的色块。 (x = 像素数)

Finding patches of certain colors with a size smaller than x. (x =number of pixels)

分段

蓝色面具

在此示例中,您可以看到分段和显示分段具有蓝色 (0,0,155,255) 的所有位置的蒙版。 有一些蓝色噪音,表示为绿色和红色区域之间以及绿色和橙色区域之间的小蓝色条纹。 如果分割的区域小于 50 像素,我想删除蓝色分割,并用蓝色区域周围的颜色替换它,而不混合任何颜色。最终结果应该只包含6种原始颜色。

理想情况下,我想对图像中的所有 6 种颜色执行此过程。

我该怎么做,是否有任何内置函数可以做到这一点?

我会根据每种颜色在(阈值)掩码上应用 findContours,并收集分段表示。然后像处理蓝色蒙版一样分别渲染每种颜色。

然后我会使用这些函数https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_contours/py_contour_features/py_contour_features.html#contour-features

例如过滤方式:area = cv2.contourArea(cnt) 标记小区域。

即 - 迭代轮廓并比较 if area < ... --> collect:

对于每个 selected 小区域,您可以检查周围环境,哪些颜色是相邻的。这可以做到,例如通过从轮廓(它是一个坐标列表)中采样一些点并在各个方向扫描并比较颜色直到找到不同的颜色。找到极值点并从那里开始可能会有所帮助,见下文:

  #... produce masked image for each color, put in masks = [] ...
    #... colors = [] ... per each mask/segmented region etc.
    for m in masks:
      bw = cv2.cvtColor(m,cv2.COLOR_BGR2GRAY)
      ret, thresh = cv2.threshold(bw,127,255,0) # or whatever appropriate params 
      contours, hierarchy = cv2.findContours(thresh, 1, 2)
      streaks = []
      for c in contours:
         if cv2.contourArea(c) < minSize:
           streaks.append(c)
           # or process directly, maybe a function here, or could simplify the contour:
           # reduce the number of points: 
           # epsilon = 0.1*cv2.arcLength(cnt,True)
           # approx = cv2.approxPolyDP(cnt,epsilon,True)
           for x,y in c: # or on the approx or with skipping ... or one point may be enough
               # check with offset... Scan in some direction until black/different color or pointPolygonTest() is False etc.
       '''

可以找到可能使扫描更有效的极值点 - c 是轮廓:

leftmost = tuple(c[c[:,:,].argmin()][0]
rightmost = tuple(c[c[:,:,].argmax()][0]

所以有了轮廓的最左边坐标,扫描应该向左,对于最右边 - 向右等。当小区域靠近图像边界时存在边界情况,则搜索应该遍历方向。

然后您可以将这些小区域的颜色更改为相邻区域的颜色 - 在表示中(一些 class 或元组)或直接在图像中使用 cv2.fillPoly(... ). fillPoly 可用于重建分割图像。

可能有几个不同颜色的相邻区域,所以如果哪种颜色对 select 很重要,则需要更多规范,例如比较这些相邻区域的面积并 selecting bigger/smaller 一个,随机等

寻找合适的算法来填充小轮廓,物体周围的颜色似乎太复杂所以我想出了(在 Todor 的帮助下)这个:


import os
import numpy as np
from PIL import Image
import time
import cv2
from joblib import Parallel, delayed

root = 'Mask/'
files = os.listdir(root)

def despeckling(file):
#for file in files: -> if you don't want to use multiple threads to compute this.
    
    imgpath = os.path.join(root, file)     
    img1 = Image.open(imgpath)             #opening file 
    img1 = img1.convert("RGB")             #convert to rgb
    pixels1 = img1.load()
    
# blue 2 green
    newimgarray0 = np.asarray(img1)
    for y in range(img1.size[1]):                  #returning an binary img with...
        for x in range(img1.size[0]):
            if pixels1 [x,y] != (0, 0, 155):       #the color you want to isolate, and ...
                pixels1[x,y] = (0,0,0)             #the background color  (black)
    img1arr = np.asarray(img1)
    grayarr1 = cv2.cvtColor(img1arr, cv2.COLOR_RGB2GRAY)   # you have to convert to grayscale as cv2.find contours can't process anything else
    contours1, hierachy = cv2.findContours(grayarr1,cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE) # returning the contours with out any extrapolation (cv2.CHAIN_APPROX_NONE) , disregarding hierachy (RETR_LIST)

    shapes1 = []                          # empty array to store the Contours in
    for contour1 in contours1:
        if cv2.contourArea(contour1) < 1000:         # specifying the minimum contour area( here it is 1000)
            shapes1.append(contour1)             # storing the contours in the shapes1

    newimgarray1 = cv2.fillPoly(newimgarray0, shapes1, color=(0,174,0))     # filling the contours, which are deemed to smal (<1000) with next color inline
    newimg1 = Image.fromarray((newimgarray1))
    
#repeat for all colors until no small patch is left.
 
    newdir = 'despeckled/'
    newimg1.save(os.path.join(newdir, file))

run = Parallel(n_jobs=-1) (delayed(despeckling)(file) for file in files)   #parallisation of the process 

因为我有 6 种颜色,这将是我要经历的顺序

蓝色->绿色,绿色->橙色,橙色->红色,红色->紫色,紫色->蓝色,蓝色->绿色,绿色->橙色,橙色->红色,红色->紫色

这样我可以确保所有小补丁现在都属于一个更大的补丁。

肯定有更好的方法来做到这一点,但这对我来说是最简单的,因为我还是个菜鸟。 :D