主頁 > 知識(shí)庫 > python使用opencv切割圖片白邊

python使用opencv切割圖片白邊

熱門標(biāo)簽:高德地圖標(biāo)注收入咋樣 萊蕪電信外呼系統(tǒng) 銀川電話機(jī)器人電話 B52系統(tǒng)電梯外呼顯示E7 怎么辦理400客服電話 地圖標(biāo)注多個(gè) 鶴壁手機(jī)自動(dòng)外呼系統(tǒng)違法嗎 沈陽防封電銷電話卡 企業(yè)微信地圖標(biāo)注

本文實(shí)例為大家分享了python使用opencv切割圖片白邊的具體代碼,可以橫切和豎切,供大家參考,具體內(nèi)容如下

廢話不多說直接上碼,分享使人進(jìn)步:

from PIL import Image
from itertools import groupby
import cv2
import datetime
import os
 
# from core.rabbitmq import MessageQueue
 
THRESHOLD_VALUE = 230  # 二值化時(shí)的閾值
PRETREATMENT_FILE = 'hq'  # 橫切時(shí)臨時(shí)保存的文件夾
W = 540  # 最小寬度
H = 960  # 最小高度
 
 
class Pretreatment(object):
    __doc__ = "圖片橫向切割"
 
    def __init__(self, path, save_path, min_size=960):
        self.x = 0
        self.y = 0
        self.img_section = []
        self.continuity_position = []
        self.path = path
        self.save_path = save_path
        self.img_obj = None
        self.min_size = min_size
        self.mkdir(self.save_path)
        self.file_name = self.path.split('/')[-1]
 
    def get_continuity_position_new(self):
        img = cv2.imread(self.path)
        gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        ret, thresh1 = cv2.threshold(gray_image, THRESHOLD_VALUE, 255, cv2.THRESH_BINARY)
 
        width = img.shape[1]
        height = img.shape[0]
        self.x = width
        self.y = height
        for i in range(0, height):
            if thresh1[i].sum() != 255 * width:
                self.continuity_position.append(i)
 
    def filter_rule(self):
        if self.y  self.min_size:
            return True
 
    def mkdir(self, path):
        if not os.path.exists(path):
            os.makedirs(path)
 
    def get_section(self):
        # 獲取區(qū)間
        for k, g in groupby(enumerate(self.continuity_position), lambda x: x[1] - x[0]):
            l1 = [j for i, j in g]  # 連續(xù)數(shù)字的列表
            if len(l1) > 1:
                self.img_section.append([min(l1), max(l1)])
 
    def split_img(self):
        print(self.img_section)
        for k, s in enumerate(self.img_section):
            if s:
                if not self.img_obj:
                    self.img_obj = Image.open(self.path)
 
                if self.x  W:
                    return
                if s[1] - s[0]  H:
                    return
                cropped = self.img_obj.crop((0, s[0], self.x, s[1]))  # (left, upper, right, lower)
                self.mkdir(os.path.join(self.save_path, PRETREATMENT_FILE))
                cropped.save(os.path.join(self.save_path, PRETREATMENT_FILE, f"hq_{k}_{self.file_name}"))
 
    def remove_raw_data(self):
        os.remove(self.path)
 
    def main(self):
        # v2
        try:
            self.get_continuity_position_new()
            self.filter_rule()
            self.get_section()
            self.split_img()
        except Exception as e:
            print(self.file_name)
            print(e)
        finally:
            if self.img_obj:
                self.img_obj.close()
 
 
class Longitudinal(Pretreatment):
    def get_continuity_position_new(self):
        print(self.path)
        img = cv2.imread(self.path)
        gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        ret, thresh1 = cv2.threshold(gray_image, THRESHOLD_VALUE, 255, cv2.THRESH_BINARY)
 
        width = img.shape[1]
        height = img.shape[0]
        print(width, height)
        self.x = width
        self.y = height
        for i in range(0, width):
            if thresh1[:, i].sum() != 255 * height:
                self.continuity_position.append(i)
 
    def split_img(self):
        print(self.img_section)
        for k, s in enumerate(self.img_section):
            if s:
                if not self.img_obj:
                    self.img_obj = Image.open(self.path)
                if self.y  H:
                    return
                if s[1] - s[0]  W:
                    return
                cropped = self.img_obj.crop((s[0], 0, s[1], self.y))  # (left, upper, right, lower)
                cropped.save(os.path.join(self.save_path, f"{k}_{self.file_name}"))
 
 
def main(path, save_path):
    starttime = datetime.datetime.now()
    a = Pretreatment(path=path, save_path=save_path)
    a.main()
    for root, dirs, files in os.walk(os.path.join(save_path, PRETREATMENT_FILE)):
        for i in files:
            b = Longitudinal(path=os.path.join(save_path, PRETREATMENT_FILE, i), save_path=save_path)
            b.main()
            os.remove(os.path.join(save_path, PRETREATMENT_FILE, i))
    endtime = datetime.datetime.now()
    print(f'耗時(shí):{(endtime - starttime)}')
 
 
if __name__ == '__main__':
    path = '你圖片存放的路徑'
    save_path = '要保存的路徑'
    for _, _, files in os.walk(path):
        for i in files:
            main(path=os.path.join(path, i), save_path=save_path)
    os.rmdir(os.path.join(save_path, PRETREATMENT_FILE))

原始圖片:

結(jié)果:

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

您可能感興趣的文章:
  • python切割圖片的示例
  • Python切割圖片成九宮格的示例代碼
  • python3 實(shí)現(xiàn)驗(yàn)證碼圖片切割的方法
  • python實(shí)現(xiàn)對任意大小圖片均勻切割的示例
  • python3 實(shí)現(xiàn)對圖片進(jìn)行局部切割的方法

標(biāo)簽:蘭州 懷化 蕪湖 廣西 紹興 吉安 呂梁 安康

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《python使用opencv切割圖片白邊》,本文關(guān)鍵詞  python,使用,opencv,切割,圖片,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《python使用opencv切割圖片白邊》相關(guān)的同類信息!
  • 本頁收集關(guān)于python使用opencv切割圖片白邊的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章