首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何有效地循环每个像素以节省时间?

如何有效地循环每个像素以节省时间?
EN

Stack Overflow用户
提问于 2022-12-03 05:23:54
回答 4查看 41关注 0票数 0

如您所知,循环遍历每个像素并使用opencv访问它们的值需要花费太长时间。作为初学者,我正在尝试学习opencv,当我尝试这种方法时,我花了大约7-10秒的时间循环图像和执行操作。

代码如下

代码语言:javascript
复制
original_image = cv2.imread(img_f)

image = np.array(original_image)
for y in range(image.shape[0]):
    for x in range(image.shape[1]):
        # remove grey background
        if 150 <= image[y, x, 0] <= 180 and \
                150 <= image[y, x, 1] <= 180 and \
                150 <= image[y, x, 2] <= 180:
            image[y, x, 0] = 0
            image[y, x, 1] = 0
            image[y, x, 2] = 0

        # remove green dashes
        if image[y, x, 0] == 0 and \
                image[y, x, 1] == 169 and \
                image[y, x, 2] == 0:
            image[y, x, 0] = 0
            image[y, x, 1] = 0
            image[y, x, 2] = 0

在上面的代码中,我只是尝试删除灰色和绿色像素的颜色。

我发现这里也有类似的问题,但我无法理解如何在我的usecase中使用numpy,因为我是python和numpy的初学者。

任何解决这一问题的帮助或建议都将不胜感激。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2022-12-03 06:03:26

您可以利用NumPy的矢量化操作来消除所有循环,这应该要快得多。

代码语言:javascript
复制
# Remove grey background
is_grey = ((150 <= image) & (image <= 180)).all(axis=2, keepdims=True)
image = np.where(is_grey, 0, image)

# Remove green dashes
is_green_dash = (image[..., 0] == 0) & (image[..., 1] == 169) & (image[..., 2] == 0)
is_green_dash = is_green_dash[..., np.newaxis]  # append a new dim at the end
image = np.where(is_green_dash, 0, image)

np.where的两个调用都依赖于NumPy的广播业

票数 3
EN

Stack Overflow用户

发布于 2022-12-03 06:37:18

提高代码性能的一种方法是使用cv2.inRange()函数查找具有所需颜色的像素,然后使用cv2.bitwise_and()函数从图像中删除这些像素。这可以比单独遍历每个像素更有效,这可能是缓慢和计算密集型的。以下是如何实现这一目标的一个例子:

代码语言:javascript
复制
import cv2
import numpy as np

# Read the image
original_image = cv2.imread('image.jpg')

# Define the colors to be removed as ranges of BGR values
grey_min = np.array([150, 150, 150], np.uint8)
grey_max = np.array([180, 180, 180], np.uint8)
green_min = np.array([0, 0, 0], np.uint8)
green_max = np.array([0, 169, 0], np.uint8)

# Use inRange() to find pixels with the desired colors
grey_mask = cv2.inRange(original_image, grey_min, grey_max)
green_mask = cv2.inRange(original_image, green_min, green_max)

# Use bitwise_and() to remove the pixels with
票数 1
EN

Stack Overflow用户

发布于 2022-12-03 05:41:01

您可以将numpy过滤应用于图像。在您的场景中,应该是:

代码语言:javascript
复制
mask_gray = (
    (150 <= image[:, :, 0]) & (image[:, :, 0] <= 180) & 
    (150 <= image[:, :, 1]) & (image[:, :, 1] <= 180) & 
    (150 <= image[:, :, 2]) & (image[:, :, 2] <= 180)
)

image[mask_gray] = 0

mask_green = (
    (image[:, :, 0] == 0) &
    (image[:, :, 1] == 169) &
    (image[:, :, 2] == 0)
)

image[mask_green] = 0

mask_graymask_green是布尔掩码

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74664212

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档