简体   繁体   English

基于RGB提取和建立的OpenCV Python中的图像像素区分

[英]Image pixel differentiation in opencv Python based on rgb extract and settling

I am using Pyton version 3.* and opencv 3.*. 我正在使用Pyton版本3. *和opencv 3. *。 In the below code I want to subtract the whole background on the basis of a corner pixel in order to get the foreground objects 在下面的代码中,我想在一个角像素的基础上减去整个背景,以获得前景对象

def background_subtract(img,l):
    print("Extract the background pixel")
    image = cv2.imread(img,cv2.IMREAD_ANYCOLOR)
    r,g,b=image[0,0]
    t,d,m= image.shape
    for i in range(t):
        for j in range(d):
            r1,g1,b1=image[i,j]
            if r1>=r:
                r1=0
            if g1>=g:
                g1=0
            if b1>=b:
                b1=0
     path='C:\\Users\\UST\\Desktop'
     if not os.path.exists(path):
     os.makedirs(path)
     cv2.imwrite(os.path.join(path,'background_subtract%d.jpg' %l),image)
     path =os.path.join(path,'%d.jpg' %l)
     print(path)
     return path

But, instead of obtaining the subtracted background image, I am getting my original image instead. 但是,不是获取减去的背景图像,而是获取原始图像。 Please help 请帮忙

You are manipulating the rgb values but not setting them: 您正在操纵rgb值,但未设置它们:

for i in range(t):
        for j in range(d):
            r1,g1,b1=image[i,j]
            if r1>=r:
                r1=0
            if g1>=g:
                g1=0
            if b1>=b:
                b1=0
            image[i,j] = [r1,g1,b1]  # this line is missing

Maybe also have a read here: Performance comparison of OpenCV-Python interfaces, cv and cv2 也许在这里也可以读一读: OpenCV-Python接口,cv和cv2的性能比较

If you are familiar with numpy, cv2 can be manipulated through that a bit faster. 如果您熟悉numpy,则可以更快地操作cv2。

Edit: 编辑:

You will have a problem with your approach though, if your border pixel is bright red (255,0,0) afterwards your picture will have a red-channel of 0, same for green and blue as you are nulling each pixels red channel if it is "less" than the one on the border. 但是,您的方法会遇到问题,如果之后边界像素为鲜红色(255,0,0),则图片的红色通道将为0,绿色和蓝色相同,因为您将每个像素的红色通道归零它比边界上的“少”。

You could play around with 你可以玩

r,g,b=image[0,0]    # border pixel
delta = 10          # similarity to border pixel 
r_range = range( r-delta, r+delta+1)  
g_range = range( g-delta, g+delta+1)
b_range = range( b-delta, b+delta+1)

and check if all 3 rgb of the pixel you currently see is in its respective range - if so, set it to [0,0,0] : 并检查您当前看到的像素的所有3 rgb是否都in各自的范围内-如果是,请将其设置为[0,0,0]

for i in range(t):
        for j in range(d):
            r1,g1,b1=image[i,j]
            if r1 in r_range and g1 in g_range and b1 in b_range:
                image[i,j] = [0,0,0]  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM