core.py 10.1 KB
Newer Older
H
hypox64 已提交
1
import os
2
import time
H
hypox64 已提交
3 4 5 6 7 8 9
import numpy as np
import cv2

from models import runmodel,loadmodel
from util import mosaic,util,ffmpeg,filt,data
from util import image_processing as impro

10 11 12
'''
---------------------Video Init---------------------
'''
H
hypox64 已提交
13 14
def video_init(opt,path):
    util.clean_tempfiles()
15 16 17
    fps,endtime,height,width = ffmpeg.get_video_infos(path)
    if opt.fps !=0:
        fps = opt.fps
H
hypox64 已提交
18
    ffmpeg.video2voice(path,'./tmp/voice_tmp.mp3')
19
    ffmpeg.video2image(path,'./tmp/video2image/output_%06d.'+opt.tempimage_type,fps)
H
hypox64 已提交
20 21
    imagepaths=os.listdir('./tmp/video2image')
    imagepaths.sort()
22
    return fps,imagepaths,height,width
H
hypox64 已提交
23

24 25 26
'''
---------------------Add Mosaic---------------------
'''
H
hypox64 已提交
27
def addmosaic_img(opt,netS):
H
hypox64 已提交
28 29 30
    path = opt.media_path
    print('Add Mosaic:',path)
    img = impro.imread(path)
H
hypox64 已提交
31
    mask = runmodel.get_ROI_position(img,netS,opt)[0]
H
hypox64 已提交
32
    img = mosaic.addmosaic(img,mask,opt)
33
    impro.imwrite(os.path.join(opt.result_dir,os.path.splitext(os.path.basename(path))[0]+'_add.jpg'),img)
H
hypox64 已提交
34

H
hypox64 已提交
35
def addmosaic_video(opt,netS):
H
hypox64 已提交
36
    path = opt.media_path
37
    fps,imagepaths = video_init(opt,path)[:2]
H
hypox64 已提交
38 39
    # get position
    positions = []
H
hypox64 已提交
40
    for i,imagepath in enumerate(imagepaths,1):
H
hypox64 已提交
41
        img = impro.imread(os.path.join('./tmp/video2image',imagepath))
H
hypox64 已提交
42
        mask,x,y,size,area = runmodel.get_ROI_position(img,netS,opt)
H
hypox64 已提交
43 44
        positions.append([x,y,area])      
        cv2.imwrite(os.path.join('./tmp/ROI_mask',imagepath),mask)
45 46
        print('Find ROI location:')
        print('\r',str(i)+'/'+str(len(imagepaths)),util.get_bar(100*i/len(imagepaths),num=35),end='')
H
hypox64 已提交
47
    print('\nOptimize ROI locations...')
H
hypox64 已提交
48 49 50
    mask_index = filt.position_medfilt(np.array(positions), 7)

    # add mosaic
51
    print('Add Mosaic:')
H
hypox64 已提交
52
    for i in range(len(imagepaths)):
H
hypox64 已提交
53
        mask = impro.imread(os.path.join('./tmp/ROI_mask',imagepaths[mask_index[i]]),'gray')
H
hypox64 已提交
54
        img = impro.imread(os.path.join('./tmp/video2image',imagepaths[i]))
55 56 57 58 59
        if impro.mask_area(mask)>100: 
            try:#Avoid unknown errors
                img = mosaic.addmosaic(img, mask, opt)
            except Exception as e:
                   print('Warning:',e)
H
hypox64 已提交
60
        cv2.imwrite(os.path.join('./tmp/addmosaic_image',imagepaths[i]),img)
61
        print('\r',str(i+1)+'/'+str(len(imagepaths)),util.get_bar(100*i/len(imagepaths),num=35),end='')
H
hypox64 已提交
62
    print()
H
hypox64 已提交
63
    ffmpeg.image2video( fps,
64
                        './tmp/addmosaic_image/output_%06d.'+opt.tempimage_type,
H
hypox64 已提交
65 66 67
                        './tmp/voice_tmp.mp3',
                         os.path.join(opt.result_dir,os.path.splitext(os.path.basename(path))[0]+'_add.mp4'))

68 69 70
'''
---------------------Style Transfer---------------------
'''
H
hypox64 已提交
71 72 73 74 75
def styletransfer_img(opt,netG):
    print('Style Transfer_img:',opt.media_path)
    img = impro.imread(opt.media_path)
    img = runmodel.run_styletransfer(opt, netG, img)
    suffix = os.path.basename(opt.model_path).replace('.pth','').replace('style_','')
76
    impro.imwrite(os.path.join(opt.result_dir,os.path.splitext(os.path.basename(opt.media_path))[0]+'_'+suffix+'.jpg'),img)
H
hypox64 已提交
77 78 79 80

def styletransfer_video(opt,netG):
    path = opt.media_path
    positions = []
81
    fps,imagepaths = video_init(opt,path)[:2]
82
    print('Transfer:')
H
hypox64 已提交
83 84 85 86
    for i,imagepath in enumerate(imagepaths,1):
        img = impro.imread(os.path.join('./tmp/video2image',imagepath))
        img = runmodel.run_styletransfer(opt, netG, img)
        cv2.imwrite(os.path.join('./tmp/style_transfer',imagepath),img)
87
        print('\r',str(i)+'/'+str(len(imagepaths)),util.get_bar(100*i/len(imagepaths),num=35),end='')
H
hypox64 已提交
88 89 90
    print()
    suffix = os.path.basename(opt.model_path).replace('.pth','').replace('style_','')
    ffmpeg.image2video( fps,
91
                './tmp/style_transfer/output_%06d.'+opt.tempimage_type,
H
hypox64 已提交
92 93 94
                './tmp/voice_tmp.mp3',
                 os.path.join(opt.result_dir,os.path.splitext(os.path.basename(path))[0]+'_'+suffix+'.mp4'))  

95 96 97 98 99 100
'''
---------------------Clean Mosaic---------------------
'''
def get_mosaic_positions(opt,netM,imagepaths,savemask=True):
    # get mosaic position
    positions = []
101 102 103 104
    t1 = time.time()
    if not opt.no_preview:
        cv2.namedWindow('mosaic mask', cv2.WINDOW_NORMAL)
    print('Find mosaic location:')
105 106 107
    for i,imagepath in enumerate(imagepaths,1):
        img_origin = impro.imread(os.path.join('./tmp/video2image',imagepath))
        x,y,size,mask = runmodel.get_mosaic_position(img_origin,netM,opt)
108 109 110
        if not opt.no_preview:
            cv2.imshow('mosaic mask',mask)
            cv2.waitKey(1) & 0xFF
111 112 113
        if savemask:
            cv2.imwrite(os.path.join('./tmp/mosaic_mask',imagepath), mask)
        positions.append([x,y,size])
114 115 116 117
        t2 = time.time()
        print('\r',str(i)+'/'+str(len(imagepaths)),util.get_bar(100*i/len(imagepaths),num=35),util.counttime(t1,t2,i,len(imagepaths)),end='')
    if not opt.no_preview:
        cv2.destroyAllWindows()
118 119 120
    print('\nOptimize mosaic locations...')
    positions =np.array(positions)
    for i in range(3):positions[:,i] = filt.medfilt(positions[:,i],opt.medfilt_num)
121
    np.save('./positions.npy', positions)
122 123
    return positions

H
hypox64 已提交
124 125
def cleanmosaic_img(opt,netG,netM):

H
hypox64 已提交
126 127 128
    path = opt.media_path
    print('Clean Mosaic:',path)
    img_origin = impro.imread(path)
H
hypox64 已提交
129
    x,y,size,mask = runmodel.get_mosaic_position(img_origin,netM,opt)
H
hypox64 已提交
130
    cv2.imwrite('./mask/'+os.path.basename(path), mask)
H
hypox64 已提交
131
    img_result = img_origin.copy()
132
    if size > 100 :
H
hypox64 已提交
133
        img_mosaic = img_origin[y-size:y+size,x-size:x+size]
134 135 136 137
        if opt.traditional:
            img_fake = runmodel.traditional_cleaner(img_mosaic,opt)
        else:
            img_fake = runmodel.run_pix2pix(img_mosaic,netG,opt)
H
hypox64 已提交
138
        img_result = impro.replace_mosaic(img_origin,img_fake,mask,x,y,size,opt.no_feather)
H
hypox64 已提交
139 140
    else:
        print('Do not find mosaic')
141
    impro.imwrite(os.path.join(opt.result_dir,os.path.splitext(os.path.basename(path))[0]+'_clean.jpg'),img_result)
H
hypox64 已提交
142

H
hypox64 已提交
143
def cleanmosaic_video_byframe(opt,netG,netM):
H
hypox64 已提交
144
    path = opt.media_path
145
    fps,imagepaths = video_init(opt,path)[:2]
H
hypox64 已提交
146
    positions = get_mosaic_positions(opt,netM,imagepaths,savemask=True)
147 148 149 150
    t1 = time.time()
    if not opt.no_preview:
        cv2.namedWindow('clean', cv2.WINDOW_NORMAL)

H
hypox64 已提交
151
    # clean mosaic
152
    print('Clean Mosaic:')
H
hypox64 已提交
153 154 155 156
    for i,imagepath in enumerate(imagepaths,0):
        x,y,size = positions[i][0],positions[i][1],positions[i][2]
        img_origin = impro.imread(os.path.join('./tmp/video2image',imagepath))
        img_result = img_origin.copy()
157 158 159 160 161 162 163 164 165 166 167
        if size > 100:
            try:#Avoid unknown errors
                img_mosaic = img_origin[y-size:y+size,x-size:x+size]
                if opt.traditional:
                    img_fake = runmodel.traditional_cleaner(img_mosaic,opt)
                else:
                    img_fake = runmodel.run_pix2pix(img_mosaic,netG,opt)
                mask = cv2.imread(os.path.join('./tmp/mosaic_mask',imagepath),0)
                img_result = impro.replace_mosaic(img_origin,img_fake,mask,x,y,size,opt.no_feather)
            except Exception as e:
                print('Warning:',e)
H
hypox64 已提交
168
        cv2.imwrite(os.path.join('./tmp/replace_mosaic',imagepath),img_result)
169 170 171 172 173 174
        #preview result
        if not opt.no_preview:
            cv2.imshow('clean',img_result)
            cv2.waitKey(1) & 0xFF
        t2 = time.time()
        print('\r',str(i+1)+'/'+str(len(imagepaths)),util.get_bar(100*i/len(imagepaths),num=35),util.counttime(t1,t2,i+1,len(imagepaths)),end='')
H
hypox64 已提交
175
    print()
176 177 178
    if not opt.no_preview:
        cv2.destroyAllWindows()
    # to video
H
hypox64 已提交
179
    ffmpeg.image2video( fps,
180
                './tmp/replace_mosaic/output_%06d.'+opt.tempimage_type,
H
hypox64 已提交
181 182 183
                './tmp/voice_tmp.mp3',
                 os.path.join(opt.result_dir,os.path.splitext(os.path.basename(path))[0]+'_clean.mp4'))  

H
hypox64 已提交
184
def cleanmosaic_video_fusion(opt,netG,netM):
H
hypox64 已提交
185 186
    path = opt.media_path
    N = 25
H
HypoX64 已提交
187 188 189 190
    if 'HD' in os.path.basename(opt.model_path):
        INPUT_SIZE = 256
    else:
        INPUT_SIZE = 128
191 192 193
    fps,imagepaths,height,width = video_init(opt,path)
    positions = get_mosaic_positions(opt,netM,imagepaths,savemask=True)
    
H
hypox64 已提交
194
    # clean mosaic
195
    print('Clean Mosaic:')
196
    img_pool = np.zeros((height,width,3*N), dtype='uint8')
H
hypox64 已提交
197 198
    for i,imagepath in enumerate(imagepaths,0):
        x,y,size = positions[i][0],positions[i][1],positions[i][2]
199 200
        
        # image read stream
H
hypox64 已提交
201
        mask = cv2.imread(os.path.join('./tmp/mosaic_mask',imagepath),0)
202 203 204 205 206 207 208
        if i==0 :
            for j in range(0,N):
                img_pool[:,:,j*3:(j+1)*3] = impro.imread(os.path.join('./tmp/video2image',imagepaths[np.clip(i+j-12,0,len(imagepaths)-1)]))
        else:
            img_pool[:,:,0:(N-1)*3] = img_pool[:,:,3:N*3]
            img_pool[:,:,(N-1)*3:] = impro.imread(os.path.join('./tmp/video2image',imagepaths[np.clip(i+12,0,len(imagepaths)-1)]))
        img_origin = img_pool[:,:,int((N-1)/2)*3:(int((N-1)/2)+1)*3]
209
        img_result = img_origin.copy()
210

211 212 213 214 215 216 217
        if size>100:
            try:#Avoid unknown errors
                #reshape to network input shape
                mosaic_input = np.zeros((INPUT_SIZE,INPUT_SIZE,3*N+1), dtype='uint8')
                mosaic_input[:,:,0:N*3] = impro.resize(img_pool[y-size:y+size,x-size:x+size,:], INPUT_SIZE)
                mask_input = impro.resize(mask,np.min(img_origin.shape[:2]))[y-size:y+size,x-size:x+size]
                mosaic_input[:,:,-1] = impro.resize(mask_input, INPUT_SIZE)
218

219 220 221 222 223 224 225 226
                mosaic_input = data.im2tensor(mosaic_input,bgr2rgb=False,use_gpu=opt.use_gpu,use_transform = False,is0_1 = False)
                unmosaic_pred = netG(mosaic_input)
                img_fake = data.tensor2im(unmosaic_pred,rgb2bgr = False ,is0_1 = False)
                img_result = impro.replace_mosaic(img_origin,img_fake,mask,x,y,size,opt.no_feather)        
            except Exception as e:
                print('Warning:',e)
        cv2.imwrite(os.path.join('./tmp/replace_mosaic',imagepath),img_result)           
        print('\r',str(i+1)+'/'+str(len(imagepaths)),util.get_bar(100*i/len(imagepaths),num=35),end='')
H
hypox64 已提交
227
    print()
H
hypox64 已提交
228
    ffmpeg.image2video( fps,
229
                './tmp/replace_mosaic/output_%06d.'+opt.tempimage_type,
H
hypox64 已提交
230 231
                './tmp/voice_tmp.mp3',
                 os.path.join(opt.result_dir,os.path.splitext(os.path.basename(path))[0]+'_clean.mp4'))