繁体   English   中英

使用OpenCL从灰度图像中过滤全白像素

[英]filtering full white pixels from a greyscale image using OpenCL

我的目标是将值= 255的图像像素转换为0.即删除所有纯白像素。 这是使用opencv和opencl的python代码:

import os
import glob
import cv2 as cv
import numpy as np
import pyopencl as cl

def filter_image( ):

    platforms = cl.get_platforms()
    devices = platforms[0].get_devices( cl.device_type.ALL )
    context = cl.Context( [devices[0]] )
    cQ = cl.CommandQueue( context )
    kernel = """
        __kernel void filter( global uchar* a, global uchar* b ){
                int y = get_global_id(0);
                int x = get_global_id(1);

                int sizex = get_global_size(1);

                if( a[ y*sizex + x ] != 255 )
                        b[ y*sizex + x ] = a[ y*sizex + x ];
            }"""

    program = cl.Program( context, kernel ).build()

    for i in glob.glob("*.png"):

        image = cv.imread( i, 0 )        
        b = np.zeros_like( image, dtype = np.uint8 )
        rdBuf = cl.Buffer( 
                context,
                cl.mem_flags.READ_ONLY | cl.mem_flags.COPY_HOST_PTR,
                hostbuf = image
                          )

        wrtBuf = cl.Buffer( 
                context,
                cl.mem_flags.WRITE_ONLY,
                b.nbytes
                          )

        program.filter( cQ, image.shape, None, rdBuf, wrtBuf ).wait()
        cl.enqueue_copy( cQ, b, wrtBuf ).wait()
        cv.imshow( 'a', b )
        cv.waitKey( 0 )

def Filter( ):
    os.chdir('D:\image')
    filter_image( )
    cv.destroyAllWindows()

我面临的问题是,一旦我按照上面的程序使用循环,逻辑只适用于第一个图像。 即,仅针对第一图像去除白色像素,但是在后续图像中看不到效果,即输出图像与输入图像相同而对值为255的像素没有任何影响。这应该是简单的。 我无法找到任何解决方案。

请帮助我解决这个问题。

谢谢。

在你的内核,你不是在图像像素设置b到任何东西,如果在图像的像素a是白色的。 您应该将其更改为以下内容:

b[y * sizex + x] = (a[y * sizex + x] == 255) ? 0 : a[y * sizex + x];

如果图像a中的像素是白色,则将图像b中的像素设置为零,否则复制像素。 还要考虑就地进行这种操作,这样只需要一个缓冲区。

暂无
暂无

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

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