我有兩種型別的影像,它們都是對比的。
型別1:(白色和干凈的背景)

型別 2:(背景中有一些灰色紋理)

我可以應用高斯模糊和閾值來處理型別 2 影像以將其調整為類似于型別 1 的白色背景,如下代碼:
type2_img = cv2.imread(type2.png)
# convert to grayscale
gray = cv2.cvtColor(type2_img , cv2.COLOR_BGR2GRAY)
# threshold the image using Otsu's thresholding
thresh = cv2.threshold(gray.copy(), 0, 255, cv2.THRESH_OTSU)[1]
# convert back to RGB
type2_img = cv2.cvtColor(thresh,cv2.COLOR_GRAY2RGB)
而且,我可以得到以下結果
:
但是,我不希望對型別 1 影像應用相同的方法,因為它已經滿足條件。
那么,OpenCV 中是否有任何影像處理方法可以區分型別 2 和型別 1 的影像?
uj5u.com熱心網友回復:
您提供的type 1影像是灰度影像,而不是完全黑白影像。然而,最后一個閾值輸出影像是黑白的。
根據您的問題,我的理解是這兩者都應歸類為type 1,type 2影像示例應歸類為 2 類。
如果型別 1 始終是黑白的,您可以計算影像中 0 和 1 的數量,并檢查它們的總和是否等于影像的總像素數。
這里的一個選項是在不修改影像的情況下對兩種型別的影像進行分類,即使用影像直方圖的黑白像素百分比。
代碼
import cv2
import numpy as np
from matplotlib import pyplot as plt
from skimage import exposure
#img_path = r'hist_imgs/1.png'
#img_path = r'hist_imgs/2.png'
img_path = r'hist_imgs/3.png'
img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
cv2.imshow('Image', img)
img_pixel_count = img.shape[0] * img.shape[1]
print(img.shape)
print(img_pixel_count)
h = np.array(exposure.histogram(img, nbins=256))
bw_count = h[0][0] h[0][255]
other_count = img_pixel_count - bw_count
print('BW PIXEL COUNT: ', bw_count)
print('OTHER PIXEL COUNT: ', other_count)
bw_percentage = (bw_count * 100.0) / img_pixel_count
other_percentage = (other_count * 100.0) / img_pixel_count
print('BW PIXEL PERCENTAGE: ', bw_percentage)
print('OTHER PIXEL PERCENTAGE: ', other_percentage)
differentiate_threshold = 3.0
if other_percentage > differentiate_threshold:
print('TYPE 2: GRAYSCALE')
else:
print('TYPE 1: BLACK AND WHITE')
plt.hist(img.ravel(), 256, [0, 256])
plt.title('Histogram')
plt.show()
輸入影像
圖 1:

圖 2:

圖 3:

代碼輸出
圖 1:
(154, 74)
11396
BW PIXEL COUNT: 11079
OTHER PIXEL COUNT: 317
BW PIXEL PERCENTAGE: 97.21832221832221
OTHER PIXEL PERCENTAGE: 2.781677781677782
TYPE 1: BLACK AND WHITE
圖 2:
(38, 79)
3002
BW PIXEL COUNT: 1543
OTHER PIXEL COUNT: 1459
BW PIXEL PERCENTAGE: 51.39906728847435
OTHER PIXEL PERCENTAGE: 48.60093271152565
TYPE 2: GRAYSCALE
圖 3:
(38, 79)
3002
BW PIXEL COUNT: 3002
OTHER PIXEL COUNT: 0
BW PIXEL PERCENTAGE: 100.0
OTHER PIXEL PERCENTAGE: 0.0
TYPE 1: BLACK AND WHITE
uj5u.com熱心網友回復:
要知道影像是否模糊,我會使用拉普拉斯方差。
import cv2
im1 = cv2.imread("s1.png")
im2 = cv2.imread("s2.png")
print(f"Im1: {cv2.Laplacian(im1, cv2.CV_64F).var()}")
print(f"Im2: {cv2.Laplacian(im2, cv2.CV_64F).var()}")
輸出:
Im1: 10493.1934011934
Im2: 17803.672073381236
我會在每個班級的中間設定一個閾值,查看一些火車組或示例。
希望它有效!
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/410130.html
標籤:
上一篇:如何正確地將蒙版插入原始影像?
下一篇:獲取有界多邊形的分割掩碼
