python - 使用 for 循环遍历二值化图像可能吗?
问题描述
这是我的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
我的问题:如何遍历二进制图像的每个像素?我想使用滑动窗口搜索算法。
解决方案
您的代码不起作用,因为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
推荐阅读
- python-3.x - ValueError:无法将字符串转换为浮点数:(pd.Series)
- php - 如何在 CodeIgniter 中添加指向路由的链接?
- node.js - crypto.createHmac 失败,字符串如 "face_url":"https\/\/"'
- ios - Flutter 中的新版 Google Maps SDK
- javascript - 定义浏览器性能的 Javascript 函数
- oracle - 了解 Oracle 中的特定 WHERE 子句
- python - python使用内部类作为静态类变量奇怪的行为
- android - 如何从 stateLessWidget 更新 StateFullWidget
- python - 90 天缺失数据的插值
- python - 通过列出它们的键来打印多个值