查找尺寸小于 x 的某些颜色的色块 x = 像素数

如何解决查找尺寸小于 x 的某些颜色的色块 x = 像素数

Segmentation

细分

enter image description here

蓝色面具

在此示例中,您可以看到分段和显示分段具有蓝色 (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) 标记小区域。

即 - 迭代轮廓并比较区域 收集:

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

  #... 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]

所以有轮廓的最左边的坐标,扫描应该向左和最右边 - 向右等。当小区域靠近图像边界时有边界情况,然后搜索应该迭代方向。

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

可能有几个不同颜色的相邻区域,所以如果选择哪种颜色很重要,则需要更多的规格,例如比较这些相邻区域的面积并选择较大/较小的区域,随机等。

,

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


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,155):       #the color you want to isolate,and ...
                pixels1[x,y] = (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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res