【问题标题】:Python OpenCV image editing: Faster way to edit pixelsPython OpenCV 图像编辑:更快的像素编辑方法
【发布时间】:2020-03-29 11:25:58
【问题描述】:

使用 python(openCV2、tkinter 等)我创建了一个应用程序(一个非常业余的应用程序)来将蓝色像素更改为白色。图像是高质量的 jpg 或 PNGS。

过程:搜索图像的每个像素,如果 BGR 的 'b' 值高于 x,则将像素设置为白色(255、255、255)。

问题:一次处理大约150张图片,所以上面的过程需要很长时间。每次迭代大约需要 9 - 15 秒,具体取决于图像大小(调整图像大小会加快处理速度,但并不理想)。

这是代码(为简单起见,删除了 GUI 和异常处理元素):

for filename in listdir(sourcefolder):
        # Read image and set variables 
        frame = imread(sourcefolder+"/"+filename)
        rows = frame.shape[0]
        cols = frame.shape[1]

        # Search pixels. If blue, set to white. 
        for i in range(0,rows):
            for j in range(0,cols):
                if frame.item(i,j,0) > 155:
                    frame.itemset((i,j,0),255)
                    frame.itemset((i,j,1),255)
                    frame.itemset((i,j,2),255)
        imwrite(sourcecopy+"/"+filename, frame)
        #release image from memory 
        del frame     

对于提高效率/速度的任何帮助将不胜感激!

【问题讨论】:

  • 你可以使用 numpy 的 where() 方法代替你的二次循环
  • 也许你不必像在 python 中那样访问像素试试:img_bgr[mask > x] = [255, 0, 0]

标签: python opencv image-editing


【解决方案1】:

使用 cv2.threshold 创建一个使用 x 阈值的掩码。

像这样设置颜色:img_bgr[mask == 255] = [255, 0, 0]

【讨论】:

    【解决方案2】:

    从这张图片开始:

    然后使用这个:

    import cv2
    im = cv2.imread('a.png') 
    
    # Make all pixels where Blue > 150 into white
    im[im[...,0]>150] = [255,255,255]
    
    # Save result
    cv2.imwrite('result.png', im)
    

    【讨论】:

    • 太棒了!非常感谢。迭代时间降至 0.8 秒。我也对代码的简单性感到惊讶。是否同时访问所有像素?我想我的业余本能是进行详尽的迭代。再次感谢。
    • 与某些人相比,我们都是业余爱好者 - 主要是努力不断学习 :-) 它在底层使用 Numpy,并且都为我们进行了大量优化。
    猜你喜欢
    • 1970-01-01
    • 2023-03-26
    • 2016-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-07
    • 2011-07-07
    • 2018-02-19
    相关资源
    最近更新 更多