基于OpenCV的Otsu阈值掩模图像区域

2024-10-01 13:24:52 发布

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

我有图像被某些区域设置为255以不干扰感兴趣的区域。当执行Otsu阈值时,这些区域会偏移阈值。在

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

我找到了一个很好的answer方法,但是我的python实现很慢。考虑到我经常在10000张图片上运行我的脚本,更快的速度可以节省我几天的时间。在

这是我正在做的一个例子

        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。在

有人能推荐一种加快速度的方法吗?在


Tags: inimport区域imgthresholdcountnp阈值