opencv:用r>b>g提取像素

2024-03-28 15:09:01 发布

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

我试图从图像中提取只有像素与r>;b>;g与opencv在python。我不想使用.split(),因为它太慢了。有人能帮我吗?你知道吗

我试过这样的事情:(但太慢了)

b,g,r = cv2.split(resized)

ma1 = np.logical_or(r>b,b>g)

编辑,我想这样做:

img[img[2]>img[1] and  img[1]>img[0]]=0

Tags: orand图像gt编辑imgnp像素
2条回答

我不确定这是否会产生预期的结果,但这对我来说没有错误

img = cv2.imread(...)

img[ (img[:,:,2] > img[:,:,1]) & (img[:,:,1] > img[:,:,0]) ] = 0

cv2.imshow('image', img)

我不需要把它分开。你知道吗

因为cv2使用BGR而不是RGB,所以我不得不按不同的顺序进行比较。你知道吗

我可以使用

img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

但是我必须将它转换回BGR来显示它。你知道吗


顺便说一句:cv2使用numpy数组来保持img

print( type(img) )

<class 'numpy.ndarray'>

您可以这样做:

import numpy as np

# Generate random image
np.random.seed(42)
r = np.random.randint(0,256,(8,5,3), dtype=np.uint8) 

# Make space for results
res = np.zeros((8,5),dtype=np.uint8)

# Calculate mask
res[(r[...,0]>r[...,1]) & (r[...,1]>r[...,2])] = 1  

输入数组r

array([[[102, 220, 225],
        [ 95, 179,  61],
        [234, 203,  92],   < - matches
        [  3,  98, 243],
        [ 14, 149, 245]],

       [[ 46, 106, 244],
        [ 99, 187,  71],
        [212, 153, 199],
        [188, 174,  65],   < - matches
        [153,  20,  44]],

       [[203, 152, 102],   < - matches
        [214, 240,  39],
        [121,  24,  34],
        [114, 210,  65],
        [239,  39, 214]],

       [[244, 151,  25],
        [ 74, 145, 222],
        [ 14, 202,  85],
        [145, 117,  87],
        [184, 189, 221]],

       [[116, 237, 109],
        [ 85,  99, 172],
        [226, 153, 103],
        [235, 146,  36],
        [151,  62,  68]],

       [[181, 130, 160],
        [160, 166, 149],
        [  6,  69,   5],
        [ 52, 253, 112],
        [ 14,   1,   3]],

       [[ 76, 248,  87],
        [233, 212, 184],
        [235, 245,  26],
        [213, 157, 253],
        [ 68, 240,  37]],

       [[219,  91,  54],
        [129,   9,  51],
        [  0, 191,  20],
        [140,  46, 187],
        [147,   1, 254]]], dtype=uint8)

结果数组:

array([[0, 0, 1, 0, 0],
       [0, 0, 0, 1, 0],
       [1, 0, 0, 0, 0],
       [1, 0, 0, 1, 0],
       [0, 0, 1, 1, 0],
       [0, 0, 0, 0, 0],
       [0, 1, 0, 0, 0],
       [1, 0, 0, 0, 0]], dtype=uint8)

相关问题 更多 >