Skip to main content
 首页 » 编程设计

Python OpenCV图像编辑: Faster way to edit pixels

2025年05月04日15leader

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

过程:搜索图像的每个像素,如果 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      

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

请您参考如下方法:

从这张图片开始:

然后使用这个:

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)