从label_image绘制轮廓

如何解决从label_image绘制轮廓

我有一个label_image数组,并且正在派生该数组上对象的轮廓/边界。目前,我正在通过获取所有唯一标签,遍历它们然后找到每个对象的轮廓来进行此操作。就像下面的循环一样,我在其中填充标签的dict并确定轮廓的值

import cv2
import pandas as pd
import numpy as np


def extract_borders(label_image):
    labels = np.unique(label_image[label_image > 0])
    d = {}
    for label in labels:
        y = label_image == label
        y = y * 255
        y = y.astype('uint8')
        contours,hierarchy = cv2.findContours(y,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
        contours = np.squeeze(contours)
        d[label] = contours.tolist()
    df = pd.DataFrame([d]).T
    df = df.reset_index()
    df.columns = ['label','coords']
    return df


if __name__ == "__main__":
    label_img = np.array([
        [0,0],[0,2,4,3,1,0]
    ])

    res = extract_borders(label_img)
    print(res)

labels成千上万时,这可能是一个真正的瓶颈。请问有更有效的方法吗?也许有一个我不知道的功能...我希望能够将标签分配给相应的轮廓。

上面的代码打印:

   label                                             coords
0      1                   [[5,6],[5,9],[9,6]]
1      2  [[3,3],[3,12],[11,10],...
2      3  [[12,5],[10,...
3      4  [[12,[12,4],[14,[15,...

解决方法

我尝试进行以下多处理尝试,并使用6个CPU的速度提高了2.5倍:

#!/usr/bin/env python3

from multiprocessing import Pool,cpu_count,freeze_support
from functools import partial
import pandas as pd
import numpy as np
import cv2
import os

def worker(labels,label_image):
    """One worker started per CPU. Receives the label image once and a list of the labels to look for."""
    pid = os.getpid()
    print(f'Worker pid: {pid},processing {len(labels)} labels')
    d = {}
    for label in labels:
        y = label_image == label
        y = y * 255
        y = y.astype('uint8')
        contours,_ = cv2.findContours(y,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
        contours = np.squeeze(contours)
        d[label] = contours.tolist()
    return d

if __name__ == '__main__':

    freeze_support()

    # Synthesize label image: 2500 labels arranged as 50x50 image,then scaled up to some realistic size
    label_image = np.arange(2500,dtype=np.uint16).reshape((50,50))
    label_image = cv2.resize(label_image,(4000,4000),interpolation=cv2.INTER_NEAREST)

    # Get number of cores and split labels across that many workers
    processes = cpu_count()

    # UNCOMMENT FOLLOWING LINE FOR SINGLE CPU
    # processes = 1
    print(f'Using {processes} processes')

    labels = np.unique(label_image[label_image > 0])
    print(f'Unique labels detected: {labels}')

    # Chunk up the labels across the processes
    chunks = np.array_split(labels,processes)

    # Map the labels across the processes
    with Pool(processes=processes) as pool:
        result = pool.map(partial(worker,label_image=label_image),chunks)

    #print(result)

具有12个内核的采样输出

Using 12 processes
Unique labels detected: [   1    2    3 ... 2497 2498 2499]
Worker pid: 76884,processing 209 labels
Worker pid: 76886,processing 209 labels
Worker pid: 76885,processing 209 labels
Worker pid: 76888,processing 208 labels
Worker pid: 76887,processing 208 labels
Worker pid: 76889,processing 208 labels
Worker pid: 76890,processing 208 labels
Worker pid: 76893,processing 208 labels
Worker pid: 76891,processing 208 labels
Worker pid: 76892,processing 208 labels
Worker pid: 76895,processing 208 labels
Worker pid: 76894,processing 208 labels

关键字:Python,图像处理,多处理,并行,块。

,

DIPlib库具有提取图像中每个对象的链码的功能。但是,它确实要求每个对象都已连接(具有相同标签的像素必须构成一个连接的组件)。使用Mark的大型示例图像,这将使计算时间从154.8s缩短到0.781s,速度提高了200倍。我认为大部分时间都致力于将链代码转换为多边形,numpy数组,列表以及最终的pandas表。很多转换...

要注意的一件事:dip.GetImageChainCodes返回的链代码符合您的期望:它们跟踪每个对象的外部像素。但是,converting these to a polygon的作用有所不同:多边形不链接外部像素,而是在像素之间“开裂”后围绕它们 。这样做可以减少像素点。这将导致多边形更好地描述实际对象,其面积恰好比对象中像素的数量少半个像素,并且其长度更接近基础对象的周长(在离散化为一组之前)像素)。这个想法来自Steve Eddins at the MathWorks

import pandas as pd
import numpy as np
import diplib as dip
import cv2
import time

def extract_borders(label_image):
    labels = np.unique(label_image[label_image > 0])
    d = {}
    for label in labels:
        y = label_image == label
        y = y * 255
        y = y.astype('uint8')
        contours,hierarchy = cv2.findContours(y,cv2.CHAIN_APPROX_SIMPLE)
        contours = np.squeeze(contours)
        d[label] = contours.tolist()
    df = pd.DataFrame([d]).T
    df = df.reset_index()
    df.columns = ['label','coords']
    return df

def extract_borders_dip(label_image):
    cc = dip.GetImageChainCodes(label_img) # input must be an unsigned integer type
    d = {}
    for c in cc:
        d[c.objectID] = np.array(c.Polygon()).tolist()
    df = pd.DataFrame([d]).T
    df = df.reset_index()
    df.columns = ['label','coords']
    return df

if __name__ == "__main__":
    label_img = np.arange(2500,50))
    label_img = cv2.resize(label_img,interpolation=cv2.INTER_NEAREST)
    start = time.process_time()
    res = extract_borders(label_img)
    print('OP code:',time.process_time() - start)
    print(res)
    start = time.process_time()
    res = extract_borders_dip(label_img)
    print('DIPlib code: ',time.process_time() - start)
    print(res)

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

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 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 -> 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("/hires") 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<String
使用vite构建项目报错 C:\Users\ychen\work>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)> insert overwrite table dwd_trade_cart_add_inc > select data.id, > data.user_id, > data.course_id, > date_format(
错误1 hive (edu)> insert into huanhuan values(1,'haoge'); 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> 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 # 添加如下 <configuration> <property> <name>yarn.nodemanager.res