python中的图像分割

2024-09-29 21:55:25 发布

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

我有图像shape image

我正在寻找python解决方案,以打破这个图像中的形状,根据图像中的轮廓更小的部分。在

我已经在OpenCV中研究过Canny和findContours的解决方案,但它们都不适合我。在

编辑:

使用的代码:

用精明的方法

import cv2 import numpy as np

img = cv2.imread('area_of_blob_maxcontrast_white.jpg') edges = cv2.Canny(img, 100, 200)
cv2.imwrite('area_of_blob_maxcontrast_white_edges.jpg',edges)

使用findConteurs方法

^{pr2}$

Tags: of方法图像importimgarea解决方案cv2
1条回答
网友
1楼 · 发布于 2024-09-29 21:55:25

诀窍是使你的模糊的单像素边界略粗一点。我通过将任何有两个相邻的黑色像素(上、下、左或右)的白色像素更改为黑色。(不过,我做得非常慢。我很确定肯定有一种更聪明的方法可以用OpenCV或Numpy来实现。)

这是我的代码:

#!/usr/bin/env python 

import numpy as np
import cv2

THRESH = 240

orig = cv2.imread("map.png")
img = cv2.cvtColor(orig, cv2.COLOR_BGR2GRAY)

# Make the faint 1-pixel boundary bolder
rows, cols = img.shape
new_img = np.full_like(img, 255)    # pure white image
for y in range(rows):
    if not (y % 10):
        print ('Row = %d (%.2f%%)' % (y, 100.*y/rows))
    for x in range(cols):
        score  = 1 if y > 0 and img.item(y-1, x) < THRESH else 0
        score += 1 if x > 0 and img.item(y, x-1) < THRESH else 0
        score += 1 if y < rows-1 and img.item(y+1, x) < THRESH else 0
        score += 1 if x < cols-1 and img.item(y, x+1) < THRESH else 0
        if img.item(y, x) < THRESH or score >= 2:
            new_img[y, x] = 0       # black pixels show boundary

cv2.imwrite('thresh.png', new_img)

# Find all contours on the map
_th, contours, hierarchy = cv2.findContours(new_img,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
print "Number of contours detected = %d" % len(contours)

# Fill second level regions on the map
coln = 0
colors = [
    [127, 0, 255],
    [255, 0, 127],
    [255, 127, 0],
    [127, 255, 0],
    [0, 127, 255],
    [0, 255, 127],
]
hierarchy = hierarchy[0]
for i in range(len(contours)):
    area = cv2.contourArea(contours[i])
    if hierarchy[i][3] == 1:
        print (i, area)
        coln = (coln + 1) % len(colors)
        cv2.drawContours(orig, contours, i, colors[coln], -1)

cv2.imwrite("colored_map.png", orig)

输入图像:

Faint outline of regions

输出图像:

Map with four colored regions

这里我只给最外面轮廓(hierarchy[i][3] == 1)的直接后代着色。但你可以改变它来排除湖泊。在

相关问题 更多 >

    热门问题