簡體   English   中英

使用 Python OpenCV 刪除圖像的黑色標題部分

[英]Remove black header section of image using Python OpenCV

我需要使用 Python CV 刪除圖像多個部分中的變黑部分。 我嘗試去噪,但效果不佳。

例如。 我需要刪除表格標題中的黑色部分(下圖)並將標題背景轉換為白色,內容為黑色。

在此處輸入圖片說明

任何人都可以幫助我選擇正確的庫或解決方案來克服這個問題嗎?

如您所見,很難過濾虛線圖案。 它顯然與文本重疊。 我至少看到兩個選項:1)利用模式的周期性並進行頻率過濾 2) 嘗試一種更簡單的方法,對目標像素使用形態學命中或未命中操作,旨在隔離它們。

讓我們看看選項 2。噪音有一個非常獨特的模式。 如果您使用所有 blob 都塗成白色的二進制圖像,則您要查找的圖案是一個白色像素(1)被 8 個黑色像素(0)包圍:

[ 0, 0, 0 ]
[ 0, 1, 0 ]
[ 0, 0, 0 ]

命中和未命中操作可用於定位和隔離像素模式。 如果您想了解更多信息,這里有一個很好的帖子。 現在,讓我們處理代碼:

//Read the input image, as normal:
std::string imagePath = "C://opencvImages//tableTest.png";
cv::Mat testImage = cv::readImage( imagePath );

//Convert the image to grayscale:
cv::Mat grayImage;
cv::cvtColor( testImage, grayImage, cv::COLOR_BGR2GRAY );

//Get the binary image via otsu:
cv::Mat binaryImage;
cv::threshold( grayImage, binaryImage, 0, 255,cv::THRESH_OTSU );

//Invert the image, as we will be working on white blobs:
binaryImage = 255 - binaryImage;

//Prepare the target kernel. This is where you define the pattern of 
//pixels you are looking for
//Keep in mind that -1 -> black and 1 -> white

cv::Mat kernel = ( cv::Mat_<int>(3, 3) <<
    -1, -1, -1,
    -1, 1, -1,
    -1, -1, -1
);

//perform the hit or miss operation:
cv::Mat hitMissMask;
cv::morphologyEx( binaryImage, hitMissMask, cv::MORPH_HITMISS, kernel );

這是你得到的面具:

在此處輸入圖片說明

現在,只需將這個蒙版減去原始(二進制)圖像,你就會得到這個:

在此處輸入圖片說明

如您所見,部分列標題妨礙了操作。 如果您想要白色背景和黑色斑點,只需反轉圖像:

在此處輸入圖片說明

這是@eldesgraciado 方法的修改版本,該方法使用 Python 中目標像素的形態命中或未命中操作來過濾點狀圖案。 不同之處在於,我們不是用降低文本質量的二值圖像減去掩碼,而是先對二值圖像進行膨脹,然后按位擴展,以保持文本質量。

  1. 獲取二值圖像。 加載圖像、灰度、 大津閾值

  2. 執行形態命中或未命中操作。 我們創建帶點陣圖形內核cv2.getStructuringElement然后使用cv2.filter2D進行卷積圖像

  3. 去除點。 我們cv2.bitwise-xor與二值圖像的掩碼

  4. 修復損壞的文本像素。 我們cv2.dilate然后cv2.bitwise_and與輸入圖像和顏色背景像素白色的最終掩碼


二進制圖像

在此處輸入圖片說明

點掩碼

在此處輸入圖片說明

刪除點

在此處輸入圖片說明

擴張以修復閾值處理過程中損壞的文本像素

在此處輸入圖片說明

結果

在此處輸入圖片說明

代碼

import cv2
import numpy as np

# Load image, grayscale, Otsu's threshold
image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Perform morphological hit or miss operation
kernel = np.array([[-1,-1,-1], [-1,1,-1], [-1,-1,-1]])
dot_mask = cv2.filter2D(thresh, -1, kernel)

# Bitwise-xor mask with binary image to remove dots
result = cv2.bitwise_xor(thresh, dot_mask)

# Dilate to fix damaged text pixels
# since the text quality has decreased from thresholding
# then bitwise-and with input image
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2,2))
dilate = cv2.dilate(result, kernel, iterations=1)
result = cv2.bitwise_and(image, image, mask=dilate)
result[dilate==0] = [255,255,255]

cv2.imshow('dot_mask', dot_mask)
cv2.imshow('thresh', thresh)
cv2.imshow('result', result)
cv2.imshow('dilate', dilate)
cv2.waitKey()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM