python利用opencv去除图片logo_利用python和opencv批量去掉图片黑边

该博客介绍了如何使用Python和OpenCV库进行多进程处理,批量去除图片中的黑边和logo。首先,通过读取图片并转化为灰度,应用腐蚀和膨胀操作,然后模糊处理以获取最频繁的像素值作为阈值。接着,找到轮廓并计算最小外接矩形,裁剪出无黑边和logo的图像部分。整个过程实现了并发处理,提高了效率。
摘要由CSDN通过智能技术生成

import os

import cv2

import numpy as np

from scipy.stats import mode

import time

import concurrent.futures

‘‘‘

multi-process to crop pictures.

‘‘‘

def crop(file_path_list):

origin_path, save_path = file_path_list

img = cv2.imread(origin_path)

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

closed_1 = cv2.erode(gray, None, iterations=4)

closed_1 = cv2.dilate(closed_1, None, iterations=4)

blurred = cv2.blur(closed_1, (9, 9))

# get the most frequent pixel

num = mode(blurred.flat)[0][0] + 1

# the threshold depends on the mode of your images‘ pixels

num = num if num <= 30 else 1

_, thresh = cv2.threshold(blurred, num, 255, cv2.THRESH_BINARY)

# you can control the size of kernel according your need.

kernel = np.ones((13, 13), np.uint8)

closed_2 = cv2.erode(thresh, kernel, iterations=4)

closed_2 = cv2.dilate(closed_2, kernel, iterations=4)

_, cnts, _ = cv2.findContours(closed_2.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

c = sorted(cnts, key=cv2.contourArea, reverse=True)[0]

# compute the rotated bounding box of the largest contour

rect = cv2.minAreaRect(c)

box = np.int0(cv2.boxPoints(rect))

# draw a bounding box arounded the detected barcode and display the image

# cv2.drawContours(img, [box], -1, (0, 255, 0), 3)

# cv2.imshow("Image", img)

# cv2.imwrite("pic.jpg", img)

# cv2.waitKey(0)

xs = [i[0] for i in box]

ys = [i[1] for i in box]

x1 = min(xs)

x2 = max(xs)

y1 = min(ys)

y2 = max(ys)

height = y2 - y1

width = x2 - x1

crop_img = img[y1:y1 + height, x1:x1 + width]

cv2.imwrite(save_path, crop_img)

# cv2.imshow("Image", crop_img)

# cv2.waitKey(0)

print(f‘the {origin_path} finish crop, most frequent pixel is {num}‘)

def multi_process_crop(input_dir):

with concurrent.futures.ProcessPoolExecutor() as executor:

executor.map(crop, input_dir)

if __name__ == "__main__":

data_dir = ‘‘

save_dir = ‘‘

path_list = [(os.path.join(data_dir, o), os.path.join(save_dir, o)) for o in os.listdir(data_dir)]

start = time.time()

multi_process_crop(path_list)

print(f‘Total cost {time.time()-start} seconds‘)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值