把叶子和背景分开

2024-09-29 19:22:29 发布

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

我有一组图片,所有的看起来都像这片叶子:

low resolution image...

我想从背景中提取叶子,为此我使用了GrabCut算法作为here。你知道吗

作为一种不同的方法,我还使用了基于r、g和b值比率的阈值,如下所示:

import numpy as np
import cv2
import matplotlib.pyplot as plt

testImg = cv2.imread('path_to_the_image')
testImg = cv2.resize(testImg, (256, 256))
#bgImg = cv2.imread('')
#blurBg = cv2.GaussianBlur(bgImg, (5, 5), 0)
#blurBg = cv2.resize(blurBg, (256, 256))

#testImg = cv2.GaussianBlur(testImg, (5, 5), 0)
cv2.imshow('testImg', testImg)
#plt.imshow(bgImg)
cv2.waitKey(0)
#plt.show()

modiImg = testImg.copy()    
ht, wd = modiImg.shape[:2]

print(modiImg[0][0][0])

for i in range(ht):
    for j in range(wd):
        r = modiImg[i][j][0]
        g = modiImg[i][j][1]
        b = modiImg[i][j][2]

        r1 = r/g
        r2 = g/b
        r3 = r/b

        r4 = round((r1+r2+r3)/3, 1)

        if g > r and g > b:
            modiImg[i][j] = [255, 255, 255]
        elif r4 >= 1.2:
            modiImg[i][j] = [255, 255, 255]
        else:
            modiImg[i][j] = [0, 0, 0]

        # if r4 <= 1.1:
        #   modiImg[i][j] = [0, 0, 0]
        # elif g > r and g > b:
        #   modiImg[i][j] = [255, 255, 255]
        # else:
        #   modiImg[i][j] = [255, 255, 255]
        # elif r4 >= 1.2:
        #   modiImg[i][j] = [255, 255, 255]
        # else:
        #   modiImg[i][j] = [0, 0, 0]


plt.imshow(modiImg)
plt.show()

testImg = testImg.astype(float)

alpha = modiImg.astype(float) / 255

testImg = cv2.multiply(alpha, testImg)                

cv2.imshow('final', testImg/255)
cv2.waitKey(0)

但是在提取的叶子图像中,叶子上的黑点总是丢失,如下所示:

enter image description here

有没有其他方法把叶子从它的背景中分离出来,假设每幅图像只有一片叶子,背景和我的其他图像一样,叶子的位置也和这里一样。你知道吗


Tags: 方法图像importaspltcv2else背景
2条回答

您可以尝试使用HSV colormap进行图像分割。你知道吗

代码:

img =  cv2.imread('leaf.jpg')
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

# find the green color 
mask_green = cv2.inRange(hsv, (36,0,0), (86,255,255))
# find the brown color
mask_brown = cv2.inRange(hsv, (8, 60, 20), (30, 255, 200))
# find the yellow color in the leaf
mask_yellow = cv2.inRange(hsv, (21, 39, 64), (40, 255, 255))

# find any of the three colors(green or brown or yellow) in the image
mask = cv2.bitwise_or(mask_green, mask_brown)
mask = cv2.bitwise_or(mask, mask_yellow)

# Bitwise-AND mask and original image
res = cv2.bitwise_and(img,img, mask= mask)

cv2.imshow("original", img)
cv2.imshow("final image", res)
cv2.waitKey(0)
cv2.destroyAllWindows()

输出:

enter image description hereenter image description here

此外,如果将黄色的较低范围从(21, 39, 64)更改为(14, 39, 64),则会看到叶上出现的小黑点开始填充,并将进一步改善结果。你知道吗

你可能想用一种深入的学习方法。U-Net在这类任务上做得相当不错。在我看来,他们也提供了一个训练有素的模型。如果你已经安装了Matlab和Caffee,你应该能够将你的文件复制到正确的文件夹中,运行程序并收到你想要的结果。你知道吗

阈值不是一个好主意,这种任务。你的方法应该能够识别模式,而不是只看像素的颜色。你知道吗

深度学习方法的一个难题是,你要么需要一个经过训练的网络来分割叶子的RBG图像,要么需要数据(叶子的RGB图像和相应的分割)。你知道吗

相关问题 更多 >

    热门问题