您现在的位置是:网站首页> 编程资料编程资料

Python opencv应用实现图片切分操作示例_python_

2023-05-26 312人已围观

简介 Python opencv应用实现图片切分操作示例_python_

说明

之前下载来zip包的漫画,里面的图片都是两张一起的:

但是某些漫画查看软件不支持自动分屏,看起来会比较不舒服,所以只能自己动手来切分。

操作说明

Python有不少的库支持图片操作,其中比较著名的一个是OpenCV。

OpenCV是一个跨平台的计算机视觉库,Python下有它的接口实现。

Python默认不带OpenCV,所以需要先用pip下载:

OpenCV功能强大,这里用来做图片的切分其实是牛刀小试。

关于OpenCV的功能,这里不多介绍,有兴趣的可以找其它的资料。

为了在代码中使用OpenCV,首先需要import相关的库:

import cv2 # Should be install independently.

然后是读取图片:

img1 = cv2.imread(filename)

然后做切割:

 # shape[0]:height shape[1]:width shape[2]:channel # img[y0:y1, x0:x1] 0=(left up) 1=(right low) slice1 = img[0:height, width/2:width]

这里实际上就是指定图片框体,需要的两个值是左上角和右下角坐标,只是对应的方式有些诡异,不知道为什么要这样对应。

然后是回写图片:

 cv2.imwrite(getname(index1), slice1, [int(cv2.IMWRITE_PNG_COMPRESSION), 1])

此外,为了保证图片不会太大,还可以做些压缩:

 img = cv2.resize(img1, (0, 0), fx=compressratio, fy=compressratio, interpolation=cv2.INTER_NEAREST)

以上就是涉及到图片的基本代码。

代码

下面是全部的代码,将它保存到py文件中,然后与图片放到同一个目录,双击py文件就可以执行,并进行图片切分:

#!/usr/bin/env python # --------------------------------------------------------------------------------- # coding=utf-8 # @File : sliceImage.py # @Author : Jiangwei # @Date : 2020/4/18 # @Desc : Slice images. # @History : # Date Author Description # 20200418 Jiangwei Created. # @Warning: # Tested in Python 2.7. # --------------------------------------------------------------------------------- import os import sys import cv2 # Should be install independently. todir = "tmp" exts = ['.jpg', '.JPG', '.png', '.PNG'] compressratio = 0.75 def listimage(adir): ''' adir : The directory name. ''' list = [] for i in os.listdir(adir): if os.path.splitext(i)[1] in exts: list.append(os.path.join(adir, i)) return list def getname(index): page = "Image%03d.png" % index return os.getcwd() + "\\" + todir + "\\" + page def doslice(filename, index1, index2): img1 = cv2.imread(filename) img = cv2.resize(img1, (0, 0), fx=compressratio, fy=compressratio, interpolation=cv2.INTER_NEAREST) height,width = img.shape[0:2] # shape[0]:height shape[1]:width shape[2]:channel # img[y0:y1, x0:x1] 0=(left up) 1=(right low) slice1 = img[0:height, width/2:width] cv2.imwrite(getname(index1), slice1, [int(cv2.IMWRITE_PNG_COMPRESSION), 1]) print getname(index1) slice2 = img[0:height, 0:width/2] cv2.imwrite(getname(index2), slice2, [int(cv2.IMWRITE_PNG_COMPRESSION), 1]) print getname(index2) return if __name__ == "__main__": ''' Slice images. ''' # Temperature directory for sliceped images. if not os.path.exists(todir): os.mkdir(todir) # Transverse all files and do the slice. imagelist = listimage (os.getcwd()) index = 1 for i in imagelist: print "Processing %s" % i doslice(i, index, index + 1) index += 2

切分之后的文件会放到新创建的tmp目录下。

切换效果

下面是切换之后的效果:

代码写得不怎么样,不过能够用......

以上就是Python opencv应用实现图片切分操作示例的详细内容,更多关于Python opencv图片切分的资料请关注其它相关文章!

-六神源码网