gpt4 book ai didi

python - 使用 OpenCV 为 Otsu 阈值蒙版图像区域

转载 作者:太空宇宙 更新时间:2023-11-03 22:53:02 27 4
gpt4 key购买 nike

我有图像,某些区域设置为 255 以不干扰感兴趣的区域。在做 Otsu 阈值时,这些区域会抵消阈值。

Image with whited-out areas that throw off the Otsu threshold

我找到了一个很好的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]

关于python - 使用 OpenCV 为 Otsu 阈值蒙版图像区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35538778/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com