我有以下圖片:
.
我只想保留黑色文本 0790 并從圖片中洗掉所有內容。這個 stackoverflow 問題教你去除顏色。但是,我需要保留顏色,而不是洗掉它。
uj5u.com熱心網友回復:
一個可能的解決方案包括將影像轉換為CMYK色彩空間并提取K(關鍵 - 黑色)通道,對其進行閾值處理并應用一些形態來清理二值影像。
OpenCV 沒有實作從BGRto的轉換CMYK,所以我們必須K手動計算通道。代碼如下所示:
# Imports
import cv2
import numpy as np
# Read image
imagePath = "D://opencvImages//"
inputImage = cv2.imread(imagePath "A6RXi.png")
# Conversion to CMYK (just the K channel):
# Convert to float and divide by 255:
imgFloat = inputImage.astype(np.float) / 255.
# Calculate channel K:
kChannel = 1 - np.max(imgFloat, axis=2)
# Convert back to uint 8:
kChannel = (255 * kChannel).astype(np.uint8)
這是 K(黑色)通道:
現在,使用固定值對影像進行閾值處理。在這種情況下,我將閾值設定為190:
# Threshold image:
binaryThresh = 190
_, binaryImage = cv2.threshold(kChannel, binaryThresh, 255, cv2.THRESH_BINARY)
這是二進制影像:
這是一個小噪音,但如果我們實作區域過濾器,我們可以去除較小的斑點。該函式在本文末尾定義。讓我們應用最小值為的過濾器100。所有小于此值的 blob 都將被擦除:
# Filter small blobs:
minArea = 100
binaryImage = areaFilter(minArea, binaryImage)
這是過濾后的影像:
涼爽的。讓我們用一個封閉過濾器來改善 blob 的形態:
# Use a little bit of morphology to clean the mask:
# Set kernel (structuring element) size:
kernelSize = 3
# Set morph operation iterations:
opIterations = 2
# Get the structuring element:
morphKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (kernelSize, kernelSize))
# Perform closing:
binaryImage = cv2.morphologyEx(binaryImage, cv2.MORPH_CLOSE, morphKernel, None, None, opIterations, cv2.BORDER_REFLECT101)
cv2.imshow("binaryImage [closed]", binaryImage)
cv2.waitKey(0)
這是最終結果:
這就是areaFilter功能。它接收一個最小面積和一個二值影像,它回傳沒有小斑點的影像:
def areaFilter(minArea, inputImage):
# Perform an area filter on the binary blobs:
componentsNumber, labeledImage, componentStats, componentCentroids = \
cv2.connectedComponentsWithStats(inputImage, connectivity=4)
# Get the indices/labels of the remaining components based on the area stat
# (skip the background component at index 0)
remainingComponentLabels = [i for i in range(1, componentsNumber) if componentStats[i][4] >= minArea]
# Filter the labeled pixels based on the remaining labels,
# assign pixel intensity to 255 (uint8) for the remaining pixels
filteredImage = np.where(np.isin(labeledImage, remainingComponentLabels) == True, 255, 0).astype('uint8')
return filteredImage
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/382338.html
