我想生成一个阈值输出。还有我的错误:
img_thres = n_pix [y,x]
TypeError:“ int”对象不可下标
import cv2
import numpy as np
import matplotlib as plt
img = cv2.imread("cicek.png",0)
img_rgb = cv2.imread("cicek.png")
h = img.shape[0]
w = img.shape[1]
img_thres= []
n_pix = 0
# loop over the image, pixel by pixel
for y in range(0, h):
for x in range(0, w):
# threshold the pixel
pixel = img[y, x]
if pixel < 0.5:
n_pix = 0
img_thres = n_pix[y, x]
cv2.imshow("cicek", img_thres)
答案 0 :(得分:2)
由于您已经在使用 OpenCV ,因此也可以使用其优化的SIMD代码进行阈值设置。它不仅更短,更容易维护,而且速度更快。看起来像这样:
_, thres = cv2.threshold(img,127,255,cv2.THRESH_TOZERO)
是的,就是这样!那将替换您所有的代码。
基准测试和演示
我大量借鉴其他答案,
for
循环的方法,并在 IPython 内运行了一些计时测试。因此,我将此代码另存为thresh.py
#!/usr/bin/env python3
import cv2
import numpy as np
def method1(img):
"""Double loop over pixels"""
h = img.shape[0]
w = img.shape[1]
img_thres= np.zeros((h,w))
# loop over the image, pixel by pixel
for y in range(0, h):
for x in range(0, w):
# threshold the pixel
pixel = img[y, x]
img_thres[y, x] = 0 if pixel < 128 else pixel
return img_thres
def method2(img):
"""Numpy indexing"""
img_thres = img
img_thres[ img < 128 ] = 0
return img_thres
def method3(img):
"""OpenCV thresholding"""
_, thres = cv2.threshold(img,127,255,cv2.THRESH_TOZERO)
return thres
img = cv2.imread("gradient.png",cv2.IMREAD_GRAYSCALE)
然后,我启动了 IPython 并做到了:
%load thresh.py
然后,我对三种方法进行计时:
%timeit method1(img)
81 ms ± 545 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit method2(img)
24.5 µs ± 818 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit method3(img)
3.03 µs ± 79.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
请注意,第一个结果以毫秒为单位,而其他两个结果以微秒为单位。 Numpy版本比for循环快3,300倍,而OpenCV版本比快循环快27,000倍!!!
您可以像这样添加图像中的差异来检查它们是否产生相同的结果:
np.sum(method1(img)-method3(img))
0.0
起始图片:
结果图片:
答案 1 :(得分:1)
要对图像应用阈值,只需执行以下操作:
img_thres = img >= 0.5
您不需要任何循环即可进行阈值设置。
如果从您的代码看来,您不想阈值,而是将所有值都小于0.5的像素设置为0到0,则可以将因“逻辑索引”的阈值而产生的二进制图像用作如下:
img_thres = img
img_thres[ img < 0.5 ] = 0
使用NumPy向量化操作的代码总是比在每个数组元素上显式循环的代码更有效。
答案 2 :(得分:1)
尝试一下
import cv2
import numpy as np
import matplotlib as plt
img = cv2.imread("cicek.png",0)
img_rgb = cv2.imread("cicek.png")
h = img.shape[0]
w = img.shape[1]
img_thres= np.zeros((h,w))
n_pix = 0
# loop over the image, pixel by pixel
for y in range(0, h):
for x in range(0, w):
# threshold the pixel
pixel = img[y, x]
if pixel < 128: # because pixel value will be between 0-255.
n_pix = 0
else:
n_pix = pixel
img_thres[y, x] = n_pix
cv2.imshow("cicek", img_thres)