广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python怎么实现图像分割
  • 255
分享到

Python怎么实现图像分割

2023-06-29 09:06:36 255人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

本篇内容介绍了“python怎么实现图像分割”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!方法一import randomimpo

本篇内容介绍了“python怎么实现图像分割”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

方法一

import randomimport numpy as npfrom PIL import Image, ImageOps, ImageFilterfrom skimage.filters import gaussianimport torchimport mathimport numbersimport randomclass RandomVerticalFlip(object):    def __call__(self, img):        if random.random() < 0.5:            return img.transpose(Image.FLIP_TOP_BOTTOM)        return imGClass DeNORMalize(object):    def __init__(self, mean, std):        self.mean = mean        self.std = std    def __call__(self, tensor):        for t, m, s in zip(tensor, self.mean, self.std):            t.mul_(s).add_(m)        return tensorclass MaskToTensor(object):    def __call__(self, img):        return torch.from_numpy(np.array(img, dtype=np.int32)).long()class FreeScale(object):    def __init__(self, size, interpolation=Image.BILINEAR):        self.size = tuple(reversed(size))  # size: (h, w)        self.interpolation = interpolation    def __call__(self, img):        return img.resize(self.size, self.interpolation)class FlipChannels(object):    def __call__(self, img):        img = np.array(img)[:, :, ::-1]        return Image.fromarray(img.astype(np.uint8))class RandomGaussianBlur(object):    def __call__(self, img):        sigma = 0.15 + random.random() * 1.15        blurred_img = gaussian(np.array(img), sigma=sigma, multichannel=True)        blurred_img *= 255        return Image.fromarray(blurred_img.astype(np.uint8))# 组合class Compose(object):    def __init__(self, transforms):        self.transforms = transforms    def __call__(self, img, mask):        assert img.size == mask.size        for t in self.transforms:            img, mask = t(img, mask)        return img, mask# 随机裁剪class RandomCrop(object):    def __init__(self, size, padding=0):        if isinstance(size, numbers.Number):            self.size = (int(size), int(size))        else:            self.size = size        self.padding = padding    def __call__(self, img, mask):        if self.padding > 0:            img = ImageOps.expand(img, border=self.padding, fill=0)            mask = ImageOps.expand(mask, border=self.padding, fill=0)        assert img.size == mask.size        w, h = img.size        th, tw = self.size        if w == tw and h == th:            return img, mask        if w < tw or h < th:            return img.resize((tw, th), Image.BILINEAR), mask.resize((tw, th), Image.NEAREST)        x1 = random.randint(0, w - tw)        y1 = random.randint(0, h - th)        return img.crop((x1, y1, x1 + tw, y1 + th)), mask.crop((x1, y1, x1 + tw, y1 + th))#  中心裁剪class CenterCrop(object):    def __init__(self, size):        if isinstance(size, numbers.Number):            self.size = (int(size), int(size))        else:            self.size = size    def __call__(self, img, mask):        assert img.size == mask.size        w, h = img.size        th, tw = self.size        x1 = int(round((w - tw) / 2.))        y1 = int(round((h - th) / 2.))        return img.crop((x1, y1, x1 + tw, y1 + th)), mask.crop((x1, y1, x1 + tw, y1 + th))class RandomHorizontallyFlip(object):    def __call__(self, img, mask):        if random.random() < 0.5:            return img.transpose(Image.FLIP_LEFT_RIGHT), mask.transpose(Image.FLIP_LEFT_RIGHT)        return img, maskclass Scale(object):    def __init__(self, size):        self.size = size    def __call__(self, img, mask):        assert img.size == mask.size        w, h = img.size        if (w >= h and w == self.size) or (h >= w and h == self.size):            return img, mask        if w > h:            ow = self.size            oh = int(self.size * h / w)            return img.resize((ow, oh), Image.BILINEAR), mask.resize((ow, oh), Image.NEAREST)        else:            oh = self.size            ow = int(self.size * w / h)            return img.resize((ow, oh), Image.BILINEAR), mask.resize((ow, oh), Image.NEAREST)class RandomSizedCrop(object):    def __init__(self, size):        self.size = size    def __call__(self, img, mask):        assert img.size == mask.size        for attempt in range(10):            area = img.size[0] * img.size[1]            target_area = random.uniform(0.45, 1.0) * area            aspect_ratio = random.uniform(0.5, 2)            w = int(round(math.sqrt(target_area * aspect_ratio)))            h = int(round(math.sqrt(target_area / aspect_ratio)))            if random.random() < 0.5:                w, h = h, w            if w <= img.size[0] and h <= img.size[1]:                x1 = random.randint(0, img.size[0] - w)                y1 = random.randint(0, img.size[1] - h)                img = img.crop((x1, y1, x1 + w, y1 + h))                mask = mask.crop((x1, y1, x1 + w, y1 + h))                assert (img.size == (w, h))                return img.resize((self.size, self.size), Image.BILINEAR), mask.resize((self.size, self.size),                                                                                       Image.NEAREST)        # Fallback        scale = Scale(self.size)        crop = CenterCrop(self.size)        return crop(*scale(img, mask))class RandomRotate(object):    def __init__(self, degree):        self.degree = degree    def __call__(self, img, mask):        rotate_degree = random.random() * 2 * self.degree - self.degree        return img.rotate(rotate_degree, Image.BILINEAR), mask.rotate(rotate_degree, Image.NEAREST)class RandomSized(object):    def __init__(self, size):        self.size = size        self.scale = Scale(self.size)        self.crop = RandomCrop(self.size)    def __call__(self, img, mask):        assert img.size == mask.size        w = int(random.uniform(0.5, 2) * img.size[0])        h = int(random.uniform(0.5, 2) * img.size[1])        img, mask = img.resize((w, h), Image.BILINEAR), mask.resize((w, h), Image.NEAREST)        return self.crop(*self.scale(img, mask))class SlidingCropOld(object):    def __init__(self, crop_size, stride_rate, ignore_label):        self.crop_size = crop_size        self.stride_rate = stride_rate        self.ignore_label = ignore_label    def _pad(self, img, mask):        h, w = img.shape[: 2]        pad_h = max(self.crop_size - h, 0)        pad_w = max(self.crop_size - w, 0)        img = np.pad(img, ((0, pad_h), (0, pad_w), (0, 0)), 'constant')        mask = np.pad(mask, ((0, pad_h), (0, pad_w)), 'constant', constant_values=self.ignore_label)        return img, mask    def __call__(self, img, mask):        assert img.size == mask.size        w, h = img.size        long_size = max(h, w)        img = np.array(img)        mask = np.array(mask)        if long_size > self.crop_size:            stride = int(math.ceil(self.crop_size * self.stride_rate))            h_step_num = int(math.ceil((h - self.crop_size) / float(stride))) + 1            w_step_num = int(math.ceil((w - self.crop_size) / float(stride))) + 1            img_sublist, mask_sublist = [], []            for yy in range(h_step_num):                for xx in range(w_step_num):                    sy, sx = yy * stride, xx * stride                    ey, ex = sy + self.crop_size, sx + self.crop_size                    img_sub = img[sy: ey, sx: ex, :]                    mask_sub = mask[sy: ey, sx: ex]                    img_sub, mask_sub = self._pad(img_sub, mask_sub)                    img_sublist.append(Image.fromarray(img_sub.astype(np.uint8)).convert('RGB'))                    mask_sublist.append(Image.fromarray(mask_sub.astype(np.uint8)).convert('P'))            return img_sublist, mask_sublist        else:            img, mask = self._pad(img, mask)            img = Image.fromarray(img.astype(np.uint8)).convert('RGB')            mask = Image.fromarray(mask.astype(np.uint8)).convert('P')            return img, maskclass SlidingCrop(object):    def __init__(self, crop_size, stride_rate, ignore_label):        self.crop_size = crop_size        self.stride_rate = stride_rate        self.ignore_label = ignore_label    def _pad(self, img, mask):        h, w = img.shape[: 2]        pad_h = max(self.crop_size - h, 0)        pad_w = max(self.crop_size - w, 0)        img = np.pad(img, ((0, pad_h), (0, pad_w), (0, 0)), 'constant')        mask = np.pad(mask, ((0, pad_h), (0, pad_w)), 'constant', constant_values=self.ignore_label)        return img, mask, h, w    def __call__(self, img, mask):        assert img.size == mask.size        w, h = img.size        long_size = max(h, w)        img = np.array(img)        mask = np.array(mask)        if long_size > self.crop_size:            stride = int(math.ceil(self.crop_size * self.stride_rate))            h_step_num = int(math.ceil((h - self.crop_size) / float(stride))) + 1            w_step_num = int(math.ceil((w - self.crop_size) / float(stride))) + 1            img_slices, mask_slices, slices_info = [], [], []            for yy in range(h_step_num):                for xx in range(w_step_num):                    sy, sx = yy * stride, xx * stride                    ey, ex = sy + self.crop_size, sx + self.crop_size                    img_sub = img[sy: ey, sx: ex, :]                    mask_sub = mask[sy: ey, sx: ex]                    img_sub, mask_sub, sub_h, sub_w = self._pad(img_sub, mask_sub)                    img_slices.append(Image.fromarray(img_sub.astype(np.uint8)).convert('RGB'))                    mask_slices.append(Image.fromarray(mask_sub.astype(np.uint8)).convert('P'))                    slices_info.append([sy, ey, sx, ex, sub_h, sub_w])            return img_slices, mask_slices, slices_info        else:            img, mask, sub_h, sub_w = self._pad(img, mask)            img = Image.fromarray(img.astype(np.uint8)).convert('RGB')            mask = Image.fromarray(mask.astype(np.uint8)).convert('P')            return [img], [mask], [[0, sub_h, 0, sub_w, sub_h, sub_w]]

方法二

import numpy as npimport randomimport torchfrom torchvision import transforms as Tfrom torchvision.transforms import functional as Fdef pad_if_smaller(img, size, fill=0):    # 如果图像最小边长小于给定size,则用数值fill进行padding    min_size = min(img.size)    if min_size < size:        ow, oh = img.size        padh = size - oh if oh < size else 0        padw = size - ow if ow < size else 0        img = F.pad(img, (0, 0, padw, padh), fill=fill)    return imgclass Compose(object):    def __init__(self, transforms):        self.transforms = transforms    def __call__(self, image, target):        for t in self.transforms:            image, target = t(image, target)        return image, targetclass RandomResize(object):    def __init__(self, min_size, max_size=None):        self.min_size = min_size        if max_size is None:            max_size = min_size        self.max_size = max_size    def __call__(self, image, target):        size = random.randint(self.min_size, self.max_size)        # 这里size传入的是int类型,所以是将图像的最小边长缩放到size大小        image = F.resize(image, size)        # 这里的interpolation注意下,在torchvision(0.9.0)以后才有InterpolationMode.NEAREST        # 如果是之前的版本需要使用PIL.Image.NEAREST        target = F.resize(target, size, interpolation=T.InterpolationMode.NEAREST)        return image, targetclass RandomHorizontalFlip(object):    def __init__(self, flip_prob):        self.flip_prob = flip_prob    def __call__(self, image, target):        if random.random() < self.flip_prob:            image = F.hflip(image)            target = F.hflip(target)        return image, targetclass RandomCrop(object):    def __init__(self, size):        self.size = size    def __call__(self, image, target):        image = pad_if_smaller(image, self.size)        target = pad_if_smaller(target, self.size, fill=255)        crop_params = T.RandomCrop.get_params(image, (self.size, self.size))        image = F.crop(image, *crop_params)        target = F.crop(target, *crop_params)        return image, targetclass CenterCrop(object):    def __init__(self, size):        self.size = size    def __call__(self, image, target):        image = F.center_crop(image, self.size)        target = F.center_crop(target, self.size)        return image, targetclass ToTensor(object):    def __call__(self, image, target):        image = F.to_tensor(image)        target = torch.as_tensor(np.array(target), dtype=torch.int64)        return image, targetclass Normalize(object):    def __init__(self, mean, std):        self.mean = mean        self.std = std    def __call__(self, image, target):        image = F.normalize(image, mean=self.mean, std=self.std)        return image, target

Python怎么实现图像分割”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注编程网网站,小编将为大家输出更多高质量的实用文章!

--结束END--

本文标题: Python怎么实现图像分割

本文链接: https://www.lsjlt.com/news/323832.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Python怎么实现图像分割
    本篇内容介绍了“Python怎么实现图像分割”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!方法一import randomimpo...
    99+
    2023-06-29
  • python怎么实现图像自动阈值分割
    本文小编为大家详细介绍“python怎么实现图像自动阈值分割”,内容详细,步骤清晰,细节处理妥当,希望这篇“python怎么实现图像自动阈值分割”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。引言图像阈值分割是一种...
    99+
    2023-07-02
  • openCV实现图像分割
    本次实验为大家分享了openCV实现图像分割的具体实现代码,供大家参考,具体内容如下 一.实验目的 进一步理解图像的阈值分割方法和边缘检测方法的原理。 掌握图像基本全局阈值方法和最大...
    99+
    2022-11-12
  • python图像分割算法怎么使用
    Python中常用的图像分割算法有基于阈值的分割算法、基于边缘的分割算法和基于区域的分割算法。以下是使用这些算法的示例代码:1. 基...
    99+
    2023-10-18
    python
  • Java实现图像分割功能
    使用Java实现图像分割,供大家参考,具体内容如下 为减少动画制作过程中的IO操作,我们可以使用连续动画来改善动画播放效率。 假如我们有如下的一张图像: 如果我们对图像中的每张小图...
    99+
    2022-11-12
  • 基于OpenCV实现图像分割
    本文实例为大家分享了基于OpenCV实现图像分割的具体代码,供大家参考,具体内容如下 1、图像阈值化 源代码: #include "opencv2/highgui/highgui...
    99+
    2022-11-12
  • python+opencv图像分割如何实现分割不规则ROI区域
    这篇文章将为大家详细讲解有关python+opencv图像分割如何实现分割不规则ROI区域,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。python有哪些常用库python常用的库:1.requesuts...
    99+
    2023-06-14
  • python+opencv图像分割实现分割不规则ROI区域方法汇总
    在图像分割领域,一个重要任务便是分割出感兴趣(ROI)区域。如果是简易的矩形ROI区域其实是非常容易分割的,opencv的官方python教程里也有教到最简易的矩形ROI分割(剪裁)...
    99+
    2022-11-12
  • 怎么使用Python第三方opencv库实现图像分割处理
    这篇文章主要介绍了怎么使用Python第三方opencv库实现图像分割处理的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇怎么使用Python第三方opencv库实现图像分割处理文章都会有所收获,下面我们一起来看...
    99+
    2023-07-02
  • Python 第三方opencv库实现图像分割处理
    目录前言1.加载图片2.对图片做灰度处理3.对图片做二值化处理3.1.自定义阈值4.提取轮廓5.对轮廓画矩形框6.分割图片并保存7.查看分割图片8.完整代码前言 所需要安装的库有: ...
    99+
    2022-11-11
  • python 图像处理——图像分割及经典案例篇之基于颜色的图像分割
    前言 作者在第一部分向大家介绍了图像处理的基础知识,第二部分介绍了图像运算和图像增强,接下来第三部分我们将详细讲解图像分割及图像处理经典案例,该部分属于高阶图像处理知识,能进一步加深我们的理解和实践能...
    99+
    2023-09-04
    图像处理 python 计算机视觉
  • C++中怎么实现OpenCV图像分割与分水岭算法
    小编给大家分享一下C++中怎么实现OpenCV图像分割与分水岭算法,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!分水岭算法是一种图像区域分割法,在分割的过程中,它...
    99+
    2023-06-15
  • OpenCV基于分水岭算法的图像分割怎么实现
    本文小编为大家详细介绍“OpenCV基于分水岭算法的图像分割怎么实现”,内容详细,步骤清晰,细节处理妥当,希望这篇“OpenCV基于分水岭算法的图像分割怎么实现”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。1. ...
    99+
    2023-07-05
  • Python怎么实现位图分割的效果
    这篇文章主要讲解了“Python怎么实现位图分割的效果”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Python怎么实现位图分割的效果”吧!话不多说,直接来代码。import cv...
    99+
    2023-06-25
  • OpenCV-Python怎么使用分水岭算法实现图像分割与提取功能
    小编给大家分享一下OpenCV-Python怎么使用分水岭算法实现图像分割与提取功能,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!随着当今世界的发展,计算机视觉技...
    99+
    2023-06-15
  • 详解PythonOpenCV图像分割算法的实现
    目录前言1.图像二值化2.自适应阈值分割算法3.Otsu阈值分割算法4.基于轮廓的字符分离4.1轮廓检测 4.2轮廓绘制4.3包围框获取4.4矩形绘制 前言 图像...
    99+
    2022-11-11
  • 怎么用matlab对图像进行分割
    在MATLAB中,可以使用以下几种方法对图像进行分割:1. 基于阈值的分割:使用imbinarize函数将图像转换为二值图像。可以使...
    99+
    2023-10-08
    matlab
  • 详解Python实现图像分割增强的两种方法
    方法一 import random import numpy as np from PIL import Image, ImageOps, ImageFilter from skim...
    99+
    2022-11-13
  • python中的opencv 图像分割与提取
    目录图像分割与提取用分水岭算法实现图像分割与提取算法原理相关函数介绍分水岭算法图像分割实例交互式前景提取图像分割与提取 图像中将前景对象作为目标图像分割或者提取出来。对背景本身并无兴...
    99+
    2022-11-11
  • Tensorflow2.10实现图像分割任务示例详解
    目录前言准备大纲实现1. 获取数据2. 处理数据3. 搭建模型4. 编译、训练模型5. 预测前言 图像分割在医学成像、自动驾驶汽车和卫星成像等方面有很多应用,本质其实就是图像像素分...
    99+
    2023-01-05
    Tensorflow 图像分割 Tensorflow 分割
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作