Motive There is a place to stamp your seal on an Excel sheet or word. If it is a little important document, I sometimes want to use the same seal certificate registered in the city hall, but before, I printed the paper at a convenience store once, stamped it, scanned it again and submitted it as pdf. was doing.
I was doing a lot of analog processing, but I thought that if I could image the seal and paste it on the sheet, I wouldn't have to go to a convenience store.
At first I took a picture of the seal and tried to make the background color transparent using PowerPoint or a free image editing tool, but I gave up because I could not convert everything depending on the paper quality.
So, after trial and error, I wrote a few lines of image processing with OpenCV and solved the problem, so I will leave it as a memorandum.
Dataset I used the seal stamp sample from Akusea.
Method
Development
import cv2
import sys
import numpy as np
if __name__ == '__main__':
if len(sys.argv) != 2:
sys.exit()
window_name = "sample"
img_path = sys.argv[1]
mat = cv2.imread(img_path)
gray = cv2.cvtColor(mat, cv2.COLOR_BGR2GRAY)
cv2.imwrite("gray.png ", gray)
#Binarization
ret2, mono = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY_INV)
cv2.imwrite("mono.png ", mono)
#Masking process
dst = cv2.bitwise_and(mat,mat,mask=mono)
cv2.imwrite("dst.png ", dst)
#channel 3->Change to 4
alpha = cv2.cvtColor(dst, cv2.COLOR_BGR2BGRA)
#Only the black background is transparent
for i,col in enumerate(dst):
for j,row in enumerate(col):
color = dst[i][j]
if (color == np.array([0,0,0])).all():
alpha[i][j][3] = 0
cv2.imshow(window_name, alpha)
cv2.imwrite("out.png ", alpha)
cv2.waitKey(0)
cv2.destroyWindow(window_name)
This time, the image data processed halfway is also output.
Result
Processing flow | output |
---|---|
raw data | |
Black and white | |
Binarization+Invert | |
masking | |
Background color transparent (Processing Exit) |
Future
Background transparency can be easily created by using cv2.bitwise_and
.
If it seems that it will take time to use the tool, this one seems to be better.
Reference -Image processing with python + Opencv 5 (image combination and mask) -Alpha blending and masking of images with Python, OpenCV, NumPy -Akusea --Original data set used for seal
Recommended Posts