Anonymous
Невозможно правильно обрезать с помощью openCV в Python
Сообщение
Anonymous » 04 дек 2024, 21:16
Я хочу вырезать удостоверение личности из этого скана
Учтите, что под идентификатором много пустого пространства (пока здесь)
Сначала я предварительно обрабатываю изображение:
Код: Выделить всё
def preprocess_before_crop_2(scan_path, output_dir):
# Read the image
original_image = cv2.imread(scan_path)
# Grayscale
gray = cv2.cvtColor(original_image, cv2.COLOR_BGR2GRAY)
# Histogram Equalization on grayscale image
equalized = cv2.equalizeHist(gray)
# Initial Denoising
denoised = cv2.fastNlMeansDenoising(equalized, None, h=20, templateWindowSize=7, searchWindowSize=21)
# Sharpening kernel
kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])
sharpened = cv2.filter2D(denoised, -1, kernel)
# Bilateral filter
bilateral_filtered = cv2.bilateralFilter(sharpened, d=9, sigmaColor=75, sigmaSpace=75)
# Increase Contrast
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
contrast = clahe.apply(bilateral_filtered)
# Apply slight Gaussian blur before binarization for anti-aliasing
blurred = cv2.GaussianBlur(contrast, (3, 3), 0)
# Binary conversion with Otsu's thresholding
_, binary = cv2.threshold(blurred, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
# Adaptive thresholding
adaptive_thresh = cv2.adaptiveThreshold(blurred, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)
return adaptive_thresh
затем я обрезаю изображение:
Код: Выделить всё
def crop_document(scan_path, output_dir):
original_image = cv2.imread(scan_path)
# preprocess image
preprocessed_image = preprocess_before_crop(scan_path, output_dir)
contours, hierarchy = cv2.findContours(preprocessed_image,cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
# Find object with the biggest bounding box
mx = (0,0,0,0) # biggest bounding box so far
mx_area = 0
areas = []
for cont in contours:
x,y,w,h = cv2.boundingRect(cont)
area = w*h
ratio = float(w) / float(h)
areas.append((area,ratio))
if area > mx_area and ratio > 1:
mx = x,y,w,h
mx_area = area
x,y,w,h = mx
# Crop and save
cropped_image=original_image[y:y+h,x:x+w]
return cropped_image
Однако полученное обрезанное изображение выглядит следующим образом: (вместо этого я добавил красный прямоугольник того, что хочу обрезать)
Я пытался удалить/изменить некоторые этапы предварительной обработки, но безрезультатно.
Подробнее здесь:
https://stackoverflow.com/questions/792 ... -in-python
1733336204
Anonymous
Я хочу вырезать удостоверение личности из этого скана [img]https://i.sstatic.net/QsYdqgRn.png[/img] Учтите, что под идентификатором много пустого пространства (пока здесь) Сначала я предварительно обрабатываю изображение: [code]def preprocess_before_crop_2(scan_path, output_dir): # Read the image original_image = cv2.imread(scan_path) # Grayscale gray = cv2.cvtColor(original_image, cv2.COLOR_BGR2GRAY) # Histogram Equalization on grayscale image equalized = cv2.equalizeHist(gray) # Initial Denoising denoised = cv2.fastNlMeansDenoising(equalized, None, h=20, templateWindowSize=7, searchWindowSize=21) # Sharpening kernel kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]]) sharpened = cv2.filter2D(denoised, -1, kernel) # Bilateral filter bilateral_filtered = cv2.bilateralFilter(sharpened, d=9, sigmaColor=75, sigmaSpace=75) # Increase Contrast clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8)) contrast = clahe.apply(bilateral_filtered) # Apply slight Gaussian blur before binarization for anti-aliasing blurred = cv2.GaussianBlur(contrast, (3, 3), 0) # Binary conversion with Otsu's thresholding _, binary = cv2.threshold(blurred, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # Adaptive thresholding adaptive_thresh = cv2.adaptiveThreshold(blurred, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2) return adaptive_thresh [/code] затем я обрезаю изображение: [code]def crop_document(scan_path, output_dir): original_image = cv2.imread(scan_path) # preprocess image preprocessed_image = preprocess_before_crop(scan_path, output_dir) contours, hierarchy = cv2.findContours(preprocessed_image,cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) # Find object with the biggest bounding box mx = (0,0,0,0) # biggest bounding box so far mx_area = 0 areas = [] for cont in contours: x,y,w,h = cv2.boundingRect(cont) area = w*h ratio = float(w) / float(h) areas.append((area,ratio)) if area > mx_area and ratio > 1: mx = x,y,w,h mx_area = area x,y,w,h = mx # Crop and save cropped_image=original_image[y:y+h,x:x+w] return cropped_image [/code] Однако полученное обрезанное изображение выглядит следующим образом: (вместо этого я добавил красный прямоугольник того, что хочу обрезать) [img]https://i.sstatic.net/AJX4LWJ8.png[/img] Я пытался удалить/изменить некоторые этапы предварительной обработки, но безрезультатно. Подробнее здесь: [url]https://stackoverflow.com/questions/79247843/cannot-crop-correctly-with-opencv-in-python[/url]