Skip to content

Commit 7e3fec9

Browse files
committed
blending image
1 parent 155d48e commit 7e3fec9

File tree

4 files changed

+212
-0
lines changed

4 files changed

+212
-0
lines changed

blending.py

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import cv2 as cv
2+
import numpy as np
3+
import glob
4+
import os
5+
import logging
6+
from multiprocessing import Process
7+
8+
if not os.path.exists('logs'):
9+
os.mkdir('logs')
10+
11+
logging.basicConfig(filename='logs/blending.txt',
12+
filemode='a',
13+
format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
14+
datefmt='%H:%M:%S',
15+
level=logging.DEBUG)
16+
17+
18+
def blending(images: str, background: str, alphas: list):
19+
"""
20+
21+
"""
22+
image_paths = glob.glob(images + '/*.jpg')
23+
background_paths = glob.glob(background + '/*.jpg')
24+
for background_path in background_paths:
25+
for idx, image_path in enumerate(image_paths):
26+
# try:
27+
# imread image
28+
print(image_path)
29+
img = cv.imread(image_path)
30+
# x, y, _ = img.shape
31+
# img_cropped = img[10: y-10, 10: x+10]
32+
# cv.imwrite('test.jpg', img_cropped)
33+
# get shape to resize background
34+
shape = img.shape[1], img.shape[0]
35+
# imread and resize backround
36+
backround_name = background_path.split('/')[-1]
37+
bgr_name = backround_name.split('.')[0]
38+
img_bgr = cv.imread(background_path)
39+
bgr_resized = cv.resize(img_bgr, shape)
40+
# setup save path
41+
image_name = image_path.split('/')[-1]
42+
print(image_name)
43+
name = image_name.split('.')[0]
44+
print(name)
45+
saver = 'output_red'
46+
if not os.path.exists(saver):
47+
os.makedirs(saver)
48+
# add blending with alpha
49+
for alpha in np.asarray(alphas):
50+
dst = cv.addWeighted(img, alpha, bgr_resized, 1-alpha, 0)
51+
img_path = saver + '/{}_{}_{}_{}.jpg'.format(bgr_name, name, idx, alpha)
52+
cv.imwrite(img_path, dst)
53+
# except Exception as e:
54+
# logging.error("log blending image", exc_info=True)
55+
# continue
56+
57+
if __name__ == '__main__':
58+
59+
images = 'red_images'
60+
background = 'background'
61+
alpha = [ 0.5, 0.8]
62+
processes = []
63+
for i in range(14):
64+
p = Process(target=blending, args=(images, background, alpha))
65+
p.daemon = True
66+
p.start()
67+
processes.append(p)
68+
69+
for p in processes:
70+
p.join()

change_color_text.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import cv2
2+
import numpy as np
3+
import tqdm
4+
import glob
5+
import os
6+
import time
7+
import logging
8+
from multiprocessing import Process
9+
10+
11+
logging.basicConfig(filename='logs/change_color.txt',
12+
filemode='a',
13+
format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
14+
datefmt='%H:%M:%S',
15+
level=logging.DEBUG)
16+
17+
def change_color(images, target_1, target_2, threshold, output='color_changed'):
18+
"""
19+
Check color of each pixel
20+
if mean of all color value of each pixel bigger than threshold:
21+
color value assign for tartget_1 color
22+
else:
23+
color value assign for target_2 color
24+
"""
25+
if os.path.exists(output):
26+
os.makedirs(output)
27+
counter = []
28+
paths = glob.glob(images + '/*.jpg')
29+
for path in tqdm.tqdm(paths):
30+
start = time.time()
31+
try:
32+
img = cv2.imread(path)
33+
for i in range(img.shape[1]):
34+
for j in range(img.shape[0]):
35+
channels_xy = img[j,i]
36+
if np.mean(channels_xy) > threshold:
37+
img[j,i] = target_1
38+
else:
39+
img[j,i] = target_2
40+
saver = os.path.join(output, path.split('/')[-1])
41+
cv2.imwrite(saver, img)
42+
except Exception as e:
43+
logging.error("log exception change color text", exc_info=True)
44+
continue
45+
counter.append(time.time() - start)
46+
print("Total time: {} and average time: {}".format(sum(counter), sum(counter)/len(counter)))
47+
48+
49+
if __name__ == '__main__':
50+
51+
images = 'test'
52+
red = [0, 0, 255] # BGR
53+
white = [255, 255, 255]
54+
threshold = 120
55+
num_thread = 16
56+
change_color(images, white, red, threshold)
57+
# processes = []
58+
59+
# for i in range(num_thread):
60+
# p = Process(target=change_color, args=(images, white, red, threshold))
61+
# p.daemon = True
62+
# p.start()
63+
# processes.append(p)
64+
65+
# for p in processes:
66+
# p.join()
67+

crop.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import cv2
2+
import glob
3+
import tqdm
4+
5+
for path in tqdm.tqdm(glob.glob('output/*.jpg')):
6+
name = path.split('/')[-1]
7+
img = cv2.imread(path)
8+
h, w, _ = img.shape
9+
cropped = img[420:h-500, 400:w-400]
10+
cv2.imwrite('cropped/black/{}'.format(name), cropped)

pdf2img.py

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
from pdf2image import convert_from_path
2+
import os
3+
import random
4+
import tqdm
5+
import logging
6+
import PIL
7+
from multiprocessing import Process
8+
9+
# logging defineable
10+
logging.basicConfig(filename='logs.txt',
11+
filemode='a',
12+
format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
13+
datefmt='%H:%M:%S',
14+
level=logging.DEBUG)
15+
def convert():
16+
path_pdf = './red_pdf'
17+
path_img = './red_images'
18+
if not os.path.exists(path_img):
19+
os.mkdir(path_img)
20+
21+
# PIL.Image.MAX_IMAGE_PIXELS = 933120000
22+
# Image.MAX_IMAGE_PIXELS
23+
24+
pdfs = os.listdir(path_pdf)
25+
for idx, pdf in enumerate(tqdm.tqdm(pdfs)):
26+
try:
27+
file = os.path.join(path_pdf, pdf)
28+
name = pdf.split('.')[0]
29+
# output_filename = os.path.join(path_img, name)
30+
# #
31+
# if not os.path.exists(output_filename):
32+
# os.mkdir(output_filename)
33+
#
34+
# print("file: ", output_filename)
35+
PIL.Image.MAX_IMAGE_PIXELS = None
36+
pages = convert_from_path(file, 500)
37+
# print("pages: ", pages)
38+
for idx_page, page in enumerate(pages):
39+
page.save(path_img+'/{}_{}.jpg'.format(idx, idx_page), 'JPEG')
40+
except Exception as e:
41+
logging.error("Logging load data", exc_info=True)
42+
continue
43+
44+
def re_convert():
45+
data = 'images_1'
46+
for file in tqdm.tqdm(os.listdir(data)):
47+
try:
48+
path_file = os.path.join(data, file)
49+
if len(os.listdir(path_file)) == 0:
50+
pdf = file + '.pdf'
51+
print(path_file)
52+
PIL.Image.MAX_IMAGE_PIXELS = None
53+
pages = convert_from_path('pdf/' + pdf, 300)
54+
# print("pages: ", pages)
55+
for idx_page, page in enumerate(pages):
56+
page.save(path_file+'/{}_{}.jpg'.format(file, idx_page), 'JPEG')
57+
except Exception as e:
58+
logging.error("Logging load data", exc_info=True)
59+
continue
60+
61+
if __name__ == '__main__':
62+
convert()
63+
64+
65+

0 commit comments

Comments
 (0)