Python+OpenCV program for batch clipping of images
In the process of learning online online courses recently, I used mobile phones to intercept a lot of pictures in order to facilitate the review after class. But the interception of the picture files occupied a lot of memory, and there were black and black information areas. Want to print out these pictures as courseware to save, but the black area around will not only consume a lot of printing ink, but also print out beautiful. I look for programs on the Internet to solve my problems, and the code I get can't achieve the goal of simplicity and efficiency.
So I wrote a Python program myself, using the simple function of OpenCV library, to take batch screenshots of a large number of pictures, intercept the required parts and save them:
A large number of pictures to be processed:
I chose one of the pictures as a demonstration:
Prior to program tailoring:
For the above image, we need to remove the black areas on both sides and cut out the useful areas.
Procedure 1:
import cv2 import os """Save the file name to test.txt,Read the file name by line and operate on it.""" f = open("test.txt",'w') for root,dirs,files in os.walk("kaochong", True): # Traverse to retrieve roots, directories, files for file in files: # File traversal f.writelines("kaochong\\" + file) # Write file names by line f.write('\n') # Give me a f = open("test.txt",'r') for i in range(1,107): # 106 documents line = f.readline() # Read a row line = line.strip('\n') # Remove \n #print(line) image = cv2.imread(line) # Read the image corresponding to the file name # cropImg = image[0:1080:2, 240:1680:2] # First y range, then x range, and the third step of each is the sampling step. cropImg = image[0:1080, 240:1680] # Tailoring cv2.imwrite("kaochong1\\" + line[20:39] + ".png", cropImg) # Preservation f.close() # print(image.shape) # cv2.imshow("image", image) # print(cropImg.shape) # cv2.imshow("cropImg", cropImg) # cv2.waitKey(0)
Procedure 2:
import cv2 import os """Simplified version, read the file name, do not save, immediately operate""" for root,dirs,files in os.walk("kaochong", True): # Traverse to retrieve roots, directories, files for file in files: # File traversal line = "kaochong\\" + file #print(line) image = cv2.imread(line) # Read the image corresponding to the file name # cropImg = image[0:1080:2, 240:1680:2] # First y range, then x range, and the third step of each is the sampling step. cropImg = image[0:1080, 240:1680] # Tailoring cv2.imwrite("kaochong1\\" + line[20:39] + ".png", cropImg) # Preservation
After batch processing, the black area was removed and some images were clipped.
Cut-out demonstration pictures: