我有图像,某些区域设置为 255 以不干扰感兴趣的区域。在做 Otsu 阈值时,这些区域会抵消阈值。
我找到了一个很好的answer如何做到这一点,但我的 python 实现很慢。考虑到我在 10,000 张图像上循环运行我的脚本,更快的速度可以节省我的时间。
这是我正在做的一个例子
from __future__ import absolute_import, division, print_function
#import matplotlib.pyplot as plt
import numpy as np
import cv2
#Using the image provided in the question
img = cv2.imread('imgSubbed-15.jpg', 0)
yImg,xImg = img.shape
how_many_255 = len(np.where(img==255)[0])
tempThresImg = np.zeros((1,yImg * xImg - how_many_255), np.uint8)
count=0
for ii in range(xImg):
for jj in range(yImg):
if img[jj, ii] != 255:
tempThresImg[0, count] = img[jj, ii]
count +=1
threshold, temp = cv2.threshold(tempThresImg,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) #using otsu threshold
ret,thresh = cv2.threshold(img,threshold,255,cv2.THRESH_BINARY)
threshold1, thresh1 = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) #using otsu threshold
cv2.imshow('Standard Way', thresh1)
cv2.imshow('Removed 255s', thresh)
print('\n\nThreshold with Removal= %d \t Standard Threshold = %d \n\n' %(threshold, threshold1))
阈值是 226 和 250。
谁能推荐一种加快速度的方法?
在遵循 Miki 链接的答案之后,我意识到可以在 Python 中使用条件进行索引。显式循环需要一秒钟,索引是几毫秒。
tempThresImg = img[img != 255]
我是一名优秀的程序员,十分优秀!