可以通过二值化图像进行for循环迭代吗?

2024-04-25 13:12:48 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的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

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


Tags: inimgforherehaverangearraycv2
1条回答
网友
1楼 · 发布于 2024-04-25 13:12:48

因为threshold()返回一个由两个值组成的元组:您设置的阈值(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

相关问题 更多 >

    热门问题