新四季網

未來寶寶長什麼樣子測試(想知道你未來寶寶長什麼樣嗎)

2023-08-04 22:34:21 2

​​​​​​​​​​​​​​​​​​​​​​​此帳號為華為雲開發者社區官方運營帳號,提供全面深入的雲計算前景分析、豐富的技術乾貨、程序樣例,分享華為雲前沿資訊動態

本文分享自華為雲社區《BabyGAN:根據父母照片生成孩子照片》,作者: 山海之光。

本案例可根據一張父親和母親的正臉照片,生成孩子的照片,並且可以調節參數,看看不同性別和年齡孩子的長相。

為保證照片的生成效果,上傳父母的照片時儘量上傳能露出五官且淺色底的照片。

本案例僅用於學習交流,請勿用於其他用途。

另外,由於技術不完善的原因,生成的孩子照片可能會有扭曲或失真,你可以更換不同的父母照片,重新生成孩子照片,直到達到滿意的生成效果為止。

下面開始按步驟運行本案例。

1. 安裝所需的模塊

本步驟耗時約 4 分鐘

!pip install imutils moviepy dlib

2. 下載代碼和模型文件

import osimport moxing as moxroot_dir = '/home/ma-user/work/ma_share/'code_dir = os.path.join(root_dir, 'BabyGAN')if not os.path.exists(os.path.join(root_dir, 'BabyGAN.zip')): mox.file.copy('obs://arthur-1/BabyGAN/BabyGAN.zip', os.path.join(root_dir, 'BabyGAN.zip')) os.system('cd %s; unzip BabyGAN.zip' % root_dir)os.chdir(code_dir)

3. 加載相關模塊及模型

import cv2import mathimport pickleimport imageioimport warningsimport PIL.Imageimport numpy as npfrom glob import globfrom PIL import Imageimport tensorflow as tffrom random import randrangeimport moviepy.editor as mpyimport matplotlib.pyplot as pltfrom IPython.display import clear_outputfrom moviepy.video.io.ffmpeg_writer import FFMPEG_VideoWriterimport configimport dnnlibimport dnnlib.tflib as tflibfrom encoder.generator_model import Generator%matplotlib inlinewarnings.filterwarnings("ignore")

加載模型文件,本代碼塊只可執行一次,如果發生報錯,請 restart kernel,重新運行所有代碼

tflib.init_tfURL_FFHQ = "./karras2019stylegan-ffhq-1024x1024.pkl"with dnnlib.util.open_url(URL_FFHQ, cache_dir=config.cache_dir) as f: generator_network, discriminator_network, Gs_network = pickle.load(f)generator = Generator(Gs_network, batch_size=1, randomize_noise=False)model_scale = int(2 * (math.log(1024, 2) - 1))

age_direction = np.load('./ffhq_dataset/latent_directions/age.npy')horizontal_direction = np.load('./ffhq_dataset/latent_directions/angle_horizontal.npy')vertical_direction = np.load('./ffhq_dataset/latent_directions/angle_vertical.npy')eyes_open_direction = np.load('./ffhq_dataset/latent_directions/eyes_open.npy')gender_direction = np.load('./ffhq_dataset/latent_directions/gender.npy')smile_direction = np.load('./ffhq_dataset/latent_directions/smile.npy')

def get_watermarked(pil_image: Image) -> Image: try: image = cv2.cvtColor(np.array(pil_image), cv2.COLOR_RGB2BGR) (h, w) = image.shape[:2] image = np.dstack([image, np.ones((h, w),) * 255]) pct = 0.08 full_watermark = cv2.imread('./media/logo.png', cv2.IMREAD_UNCHANGED) (fwH, fwW) = full_watermark.shape[:2] wH = int(pct * h * 2) wW = int((wH * fwW) / fwH * 0.1) watermark = cv2.resize(full_watermark, (wH, wW), interpolation=cv2.INTER_AREA) overlay = np.zeros((h, w, 4),) (wH, wW) = watermark.shape[:2] overlay[h - wH - 10: h - 10, 10: 10 wW] = watermark output = image.copy cv2.addWeighted(overlay, 0.5, output, 1.0, 0, output) rgb_image = cv2.cvtColor(output, cv2.COLOR_BGR2RGB) return Image.fromarray(rgb_image) except: return pil_imagedef generate_final_images(latent_vector, direction, coeffs, i): new_latent_vector = latent_vector.copy new_latent_vector[:8] = (latent_vector coeffs * direction)[:8] new_latent_vector = new_latent_vector.reshape((1, 18, 512)) generator.set_dlatents(new_latent_vector) img_array = generator.generate_images[0] img = PIL.Image.fromarray(img_array, 'RGB') if size[0] >= 512: img = get_watermarked(img) img_path = "./for_animation/" str(i) ".png" img.thumbnail(animation_size, PIL.Image.ANTIALIAS) img.save(img_path) face_img.append(imageio.imread(img_path)) clear_output return imgdef generate_final_image(latent_vector, direction, coeffs): new_latent_vector = latent_vector.copy new_latent_vector[:8] = (latent_vector coeffs * direction)[:8] new_latent_vector = new_latent_vector.reshape((1, 18, 512)) generator.set_dlatents(new_latent_vector) img_array = generator.generate_images[0] img = PIL.Image.fromarray(img_array, 'RGB') if size[0] >= 512: img = get_watermarked(img) img.thumbnail(size, PIL.Image.ANTIALIAS) img.save("face.png") if download_image == True: files.download("face.png") return imgdef plot_three_images(imgB, fs=10): f, axarr = plt.subplots(1, 3, figsize=(fs, fs)) axarr[0].imshow(Image.open('./aligned_images/father_01.png')) axarr[0].title.set_text("Father's photo") axarr[1].imshow(imgB) axarr[1].title.set_text("Child's photo") axarr[2].imshow(Image.open('./aligned_images/mother_01.png')) axarr[2].title.set_text("Mother's photo") plt.setp(plt.gcf.get_axes, xticks=[], yticks=[]) plt.show

4. 準備好父親和母親的照片

本案例已各準備好一張默認的父母親照片,可在左側邊欄的文件資源管理窗口中,進入到 ma_share/BabyGAN 目錄,再進入到 father_image 或 mother_image 目錄即可看到已提供的父母親照片,如下圖所示:

如果你需更換父母親的照片,請查看本文第 11 節「更換父親和母親的照片」

if len(glob(os.path.join('./father_image', '*.jpg'))) != 1 or (not os.path.exists('./father_image/father.jpg')): raise Exception('請在 ma_share/BabyGAN/father_image 目錄下準備一張父親的照片,且命名為father.jpg')if len(glob(os.path.join('./mother_image', '*.jpg'))) != 1 or (not os.path.exists('./mother_image/mother.jpg')): raise Exception('請在 ma_share/BabyGAN/father_image 目錄下準備一張母親的照片,且命名為mother.jpg')

5. 獲取父親的臉部區域,並進行人臉對齊

!python align_images.py ./father_image ./aligned_images

查看父親的人臉

if os.path.isfile('./aligned_images/father_01.png'): pil_father = Image.open('./aligned_images/father_01.png') (fat_width, fat_height) = pil_father.size resize_fat = max(fat_width, fat_height) / 256 display(pil_father.resize((int(fat_width / resize_fat), int(fat_height / resize_fat))))else: raise ValueError('No face was found or there is more than one in the photo.')

6. 獲取母親的臉部區域,並進行人臉對齊

!python align_images.py ./mother_image ./aligned_images

查看母親的人臉

if os.path.isfile('./aligned_images/mother_01.png'): pil_mother = Image.open('./aligned_images/mother_01.png') (mot_width, mot_height) = pil_mother.size resize_mot = max(mot_width, mot_height) / 256 display(pil_mother.resize((int(mot_width / resize_mot), int(mot_height / resize_mot))))else: raise ValueError('No face was found or there is more than one in the photo.')

7. 提取人臉特徵

本步驟耗時約 3 分鐘

!python encode_images.py \ --early_stopping False \ --lr=0.25 \ --batch_size=2 \ --iterations=100 \ --output_video=False \ ./aligned_images \ ./generated_images \ ./latent_representationsif len(glob(os.path.join('./generated_images', '*.png'))) == 2: first_face = np.load('./latent_representations/father_01.npy') second_face = np.load('./latent_representations/mother_01.npy') print("Generation of latent representation is complete! Now comes the fun part.")else: raise ValueError('Something wrong. It may be impossible to read the face in the photos. Upload other photos and try again.')

8. 生成一家三口照片

請修改下面代碼中的 gender_influence 和 person_age 參數

gender_influence:性別影響因子,取值範圍[0.01, 0.99],取值越接近 0,父親的容貌影響越大,反之母親影響越大;

person_age:年齡影響因子,取值範圍[10, 50],設置該值後,將生成對應年齡的小孩的容貌。

每次修改該參數值後,重新運行下面的代碼塊,即可生成孩子的新照片

genes_influence = 0.8 # 性別影響因子,取值範圍[0.01, 0.99],取值越接近0,父親的容貌影響越大,反之母親影響越大person_age = 10 # 年齡影響因子,取值範圍[10, 50],設置該值後,將生成對應年齡的小孩的容貌style = "Default"if style == "Father's photo": lr = ((np.arange(1, model_scale 1) / model_scale) ** genes_influence).reshape((model_scale, 1)) rl = 1 - lr hybrid_face = (lr * first_face) (rl * second_face)elif style == "Mother's photo": lr = ((np.arange(1, model_scale 1) / model_scale) ** (1 - genes_influence)).reshape((model_scale, 1)) rl = 1 - lr hybrid_face = (rl * first_face) (lr * second_face)else: hybrid_face = ((1 - genes_influence) * first_face) (genes_influence * second_face)intensity = -((person_age / 5) - 6)resolution = "512"size = int(resolution), int(resolution)download_image = Falseface = generate_final_image(hybrid_face, age_direction, intensity)plot_three_images(face, fs=15)

9. 查看孩子各年齡段的容貌

請修改下面代碼中的 gender_influence 參數,該參數是性別影響因子,取值範圍[0.01, 0.99],取值越接近 0,父親的容貌影響越大,反之母親影響越大。

每次修改該參數值後,要重新運行下面的代碼塊

gender_influence = 0.8 # 性別影響因子,取值範圍[0.01, 0.99],取值越接近0,父親的容貌影響越大,反之母親影響越大!rm -rf ./for_animation!mkdir ./for_animationface_img = []hybrid_face = ((1 - gender_influence) * first_face) (gender_influence * second_face)animation_resolution = "512"animation_size = int(animation_resolution), int(animation_resolution)frames_number = 50download_image = Falsefor i in range(0, frames_number, 1): intensity = (8 * (i / (frames_number - 1))) - 4 generate_final_images(hybrid_face, age_direction, intensity, i) clear_output print(str(i) " of {} photo generated".format(str(frames_number)))for j in reversed(face_img): face_img.append(j)automatic_download = Falseif gender_influence = 0.7: animation_name = "girl.mp4"else: animation_name = "animation.mp4"imageio.mimsave('./for_animation/' animation_name, face_img)clear_outputdisplay(mpy.ipython_display('./for_animation/' animation_name, height=400, autoplay=1, loop=1))

10. 查看孩子不同性別的容貌

請修改下面代碼中的 person_age 參數,該參數是年齡影響因子,取值範圍[10, 50],設置該值後,將生成對應年齡的小孩的容貌。

每次修改該參數值後,要重新運行下面的代碼塊

person_age = 10 # 小孩的年齡,取值範圍[10, 50],設置該值後,將生成對應年齡的小孩的容貌!rm -rf ./for_animation!mkdir ./for_animationface_img = []intensity = -((person_age / 5) - 6)animation_resolution = "512"animation_size = int(animation_resolution), int(animation_resolution)frames_number = 50 # 容貌變化的圖像數,取值範圍[10, 50]download_image = Falsefor i in range(1, frames_number): gender_influence = i / frames_number hybrid_face = ((1 - gender_influence) * first_face) (gender_influence * second_face) face = generate_final_images(hybrid_face, age_direction, intensity, i) clear_output print(str(i) " of {} photo generated".format(str(frames_number)))for j in reversed(face_img): face_img.append(j)animation_name = str(person_age) "_years.mp4"imageio.mimsave('./for_animation/' animation_name, face_img)clear_outputdisplay(mpy.ipython_display('./for_animation/' animation_name, height=400, autoplay=1, loop=1))

11. 更換父親和母親的照片

接下來,你可以上傳自己感興趣的父母親照片到 father_image 和 mother_image 目錄下,重新運行代碼,即可生成新的孩子照片。

你需要按照如下規則和步驟進行:

1、參考下圖的操作,進入到 ma_share/BabyGAN 目錄;

2、準備一張父親的照片,上傳到 father_image 目錄下,命名必須為 father.jpg;(如果你不知道上傳文件到 JupyterLab 的方法,請查看此文檔)

3、準備一張母親的照片,上傳到 mother_image 目錄下,命名必須為 mother.jpg;

4、father_image 和 mother_image 目錄都只允許存在一張照片;

5、重新運行步驟 4~10 的代碼。

點擊關注,第一時間了解華為雲新鮮技術~華為雲博客_大數據博客_AI博客_雲計算博客_開發者中心-華為雲

,
同类文章
2022年虎年寶寶五行取名(2022年虎年出生的寶寶名字)

2022年虎年寶寶五行取名(2022年虎年出生的寶寶名字)

2022年虎年寶寶五行取名?崢:將「崢」字作為虎寶寶取名用字,可彰顯其大氣豪邁之感,並且寓指男孩可以英勇無畏,有一夫當關的品質且「崢」字帶有「山」字根,是2022屬虎男孩最佳字,寓意虎在山中自由的休息,順應了虎的習性,現在小編就來說說關於2022年虎年寶寶五行取名?下面內容希望能幫助到你,我們來一
uff收益怎麼樣(新晉奶爸為寶寶在穹頂之下創造一片淨土)

uff收益怎麼樣(新晉奶爸為寶寶在穹頂之下創造一片淨土)

作者:蛋蛋的淡 樓主2014年3月和老鄉LD結婚後,辛勤耕耘一年無果,壓力山大。終於在15年3月和LD一起去省婦幼檢查不孕不育。沒想到醫生突然告知,樓主晉升爸爸了!喜從天降後就著手為LD保胎。 無奈雙方父母都在老家還沒退休(那時生娃都早),樓主上班又無法照顧,遂讓LD請了長病假回老家休養
寶寶睡覺資勢大全(寶寶睡覺時最常見的8個錯誤做法)

寶寶睡覺資勢大全(寶寶睡覺時最常見的8個錯誤做法)

人的一生大概有三分之一的時間,是在睡眠中度過的。而寶寶的睡眠時間更長,一天超過一半的時間都在睡覺。所以,家長們一定要關注孩子的睡眠安全。 我們今天整理了8個孩子睡眠方面家長們最容易犯的錯誤,要注意避開。 問題1:孩子可以和父母睡一張床嗎? 不建議同睡一張床。 很多家長會覺得,孩子小
異地懷孕的概率(別人懷孕我懷葡萄)

異地懷孕的概率(別人懷孕我懷葡萄)

葡萄胎,就是胚胎的滋養層細胞異常增生,並長成一連串水泡,看起來頗似葡萄。命名是有些隨意,但非常形象。 大部分葡萄胎患者會在停經後8-12周時發生陰道出血,這時,要先去醫院驗血HCG和B超,等待檢查 葡萄胎一經確診,就需要住院清宮,至少等血HCG陰性半年後,才能再次懷孕,這
孩子打呼嚕是什麼原因導致的(小孩打呼嚕是何原因)

孩子打呼嚕是什麼原因導致的(小孩打呼嚕是何原因)

經常有家長說,孩子「打呼嚕」是最近幾天的事,不但睡覺時「打呼嚕」,就是醒後也要張著口喘氣。嬰幼兒時期的孩子睡覺時「打呼嚕」或是醒後張著口喘氣都是不正常的,應引起家長足夠的重視。 不論是小孩子還是成人,在未患任何疾病的情況下,呼吸都是通過鼻腔來完成的,是不需要張口的,呼吸是在不知不覺中進行
寶寶哭鬧如何安撫停哭(寶寶哭個不停怎麼辦)

寶寶哭鬧如何安撫停哭(寶寶哭個不停怎麼辦)

寶寶哭個不停怎麼辦?情緒安撫5s法,嬰兒有安全感,自然不哭不鬧 寶寶餓了,哭! 寶寶冷了,哭! 寶寶尿了,哭! 寶寶不舒服,還是哭! 不滿三個月的寶寶好像除了睡和吃之外,就只有哭這件事了。寶寶哭了之後,我們是應該安撫,還是放任不管呢?其實,大多數新生兒的哭鬧和生理需求有關,只有
寶寶需要坐安全座椅嗎(寶寶要坐安全座椅嗎)

寶寶需要坐安全座椅嗎(寶寶要坐安全座椅嗎)

文/徐芳老師 圖/網絡 前兩天看到小視頻,引發了很多人的討論,說的是有個警察在檢查的時候剛好攔下了一輛車,然後副駕駛就有一個孩子乖乖地繫著安全帶。還自己在說要繫上安全帶,警察就覺得很奇怪,一般的孩子都不會這麼乖,孩子說,不系安全帶就會像這個IPAD一樣,說著給警察叔叔看一個裂了一大片的I
寶寶溼疹與寶媽的飲食有關係嗎(寶寶溼疹和遺傳有關係)

寶寶溼疹與寶媽的飲食有關係嗎(寶寶溼疹和遺傳有關係)

導語:每年的9月和到第二年5月,很多家長開始不淡定了,因為孩子的溼疹反反覆覆,搞得家長那是手腳無措。 溼疹是什麼? 溼疹確實是一種病因相對比較複雜的皮膚炎症,甚至有些家長還不知道孩子為什麼得溼疹,隨著孩子慢慢的長大,溼疹就自己好了。 5個月的香香臉上這段時間長很多紅色的突出的疹子,而且
什麼辦法能緩解孕期恥骨痛(恥骨痛是怎麼回事)

什麼辦法能緩解孕期恥骨痛(恥骨痛是怎麼回事)

恥骨位於大腿根部和小腹的交界處,是骨盆前方的兩塊骨頭,這兩塊骨頭在日常中少被提及,因而多數人對其了解較少,但女性朋友對其應該並不陌生,特別是懷孕過的女性,對恥骨應該了解不少。因為部分女性在妊娠期間會出現恥骨痛,那麼恥骨痛是怎麼回事?什麼因素能誘發恥骨疼痛? 恥骨痛是什麼原因? 一、妊
孩子怎麼看懂英語字母(幾個容易讀錯的字母)

孩子怎麼看懂英語字母(幾個容易讀錯的字母)

(音頻錄製:CiCi,這期聽音頻更有收穫哦) 字母是學習英語的開始,漫長的歲月中差不多都融進我們的血液了。三歲的小朋友,26個字母眼睛都不眨就能背出來。 正是因為這種熟悉,我們對字母視若當然,絲毫不覺得讀字母會出什麼差錯。但是,由於中英文的發音習慣不同,我們在讀字母的時候,真的會一不小心就