【问题标题】:Iterate with for loop through binarized image possible?使用 for 循环遍历二值化图像可能吗?
【发布时间】:2019-04-29 13:45:46
【问题描述】:

这是我的python代码:

import cv2
img = cv2.imread("foo.jpg")

#here I can iterate trough each pixel since I have a 2D array
for x in range(img.shape[0]):
    for y in range(img.shape[1]):
    pass #maipulate each pixel

gary = cv2.cvtColor(img, COLOR_BGR2GRAY)
bin = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)

#here I can not iterate trough each pixel since I have a 1D array
for x in range(img.shape[0]):
    for y in range(img.shape[1]):
        pass

我的问题: 如何遍历二进制图像的每个像素? 我想使用滑动窗口搜索算法。

【问题讨论】:

  • 感谢您的回答。有没有其他方法可以做到这一点?
  • 建议是如何让它更快,但是我认为你很难让它工作?它给你的错误是什么?为什么不能在二进制图像中迭代?除了 gary 和 gray 的拼写错误之外,代码看起来不会失败

标签: python numpy opencv image-processing binary


【解决方案1】:

您的代码不起作用,因为threshold() 返回一个包含 2 个值的元组:您设置的阈值 (127) 和一个二进制图像。如果将它们分开,则可以使用相同的双循环来访问每个值/像素。
我已经修改了你的代码,因为那里还有几个错字。

import cv2
img = cv2.imread("foo.jpg")

#here I can iterate trough each pixel since I have a 2D array
for x in range(img.shape[0]):
    for y in range(img.shape[1]):
    pass #maipulate each pixel

gray= cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh, bin_img = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)

for x in range(bin_img.shape[0]):
    for y in range(bin_img.shape[1]):
        pass

【讨论】:

    猜你喜欢
    • 2016-01-20
    • 2011-10-05
    • 2020-06-17
    • 1970-01-01
    • 2020-11-17
    • 1970-01-01
    • 1970-01-01
    • 2021-04-02
    • 2013-02-20
    相关资源
    最近更新 更多