1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
| import cv2, os, time import numpy as np
IMG_DIR = "C:\\Users\\95711\\Desktop\\test\\" SAVE_DIR = "C:\\Users\\95711\\Desktop\\save\\" TEXT = "cyberbrain.top" MAXSCALE = 5 MINSCALE = 0 SCALESTEP = -0.2 SIZERATIO = 1.3
files = os.listdir(IMG_DIR)
for index,file in enumerate(files): thickness = 2 myFont = cv2.FONT_HERSHEY_SIMPLEX
img = cv2.imread(IMG_DIR+file) filesize = os.path.getsize(IMG_DIR+file) h, w, c = img.shape
for fontscale in np.arange(MAXSCALE,MINSCALE,SCALESTEP): if fontscale < 1: thickness = 1 textSize, baseline = cv2.getTextSize(TEXT, myFont, fontscale, thickness) ratio = textSize[0] / w if fontscale == MAXSCALE and ratio < 1/3 : break if 1/3 < ratio < 1/2: break else: myFont = cv2.FONT_HERSHEY_PLAIN textSize, baseline = cv2.getTextSize(TEXT, myFont, fontscale, thickness) ratio = textSize[0] / w putx, puty = w - textSize[0], h - textSize[1] - baseline timg = img[puty:h,putx:w] gray=cv2.cvtColor(timg,cv2.COLOR_BGR2GRAY)
if gray.mean() < 127: colorfg, colorbg = (255,255,255),(0,0,0) else: colorbg, colorfg = (255,255,255),(0,0,0)
cv2.putText(img,TEXT,(putx,h-baseline),myFont,fontscale,colorbg,thickness+2) cv2.putText(img,TEXT,(putx,h-baseline),myFont,fontscale,colorfg,thickness)
if file.endswith(".jpg"): quaType = cv2.IMWRITE_JPEG_QUALITY scale = (100,0,-1) elif file.endswith(".png"): quaType = cv2.IMWRITE_PNG_COMPRESSION scale = (0,10,1)
for quality in range(*scale): time.sleep(0.001) if not cv2.imwrite(SAVE_DIR+file,img,[quaType,quality]): print("%d:%s imwrite Error! quality:%d" % (index+1,file,quality)) break time.sleep(0.005) newfilesize = os.path.getsize(SAVE_DIR+file) sizeRatio = float(newfilesize/filesize) if sizeRatio < SIZERATIO: print("%d:%s \tFinish! quality:%d, sizeRatio:%f" % (index+1,file,quality,sizeRatio)) break
|