網頁

2023年3月28日 星期二

openai dall-e python ai修圖

這隻狗本來是有牽繩的,旁邊的玩具車是ai添加的,影子的方向也處理了,這就是openai dall-e修圖。塗鴉的另外一大目的,就是ai人工智慧(不是工人智慧)修圖的前置作業,因為openai有提供python介面,就直接用python。curl也有但比較是指令集!python code請開:
print('使用openai的api進行DALL-E AI修圖生成')

!pip install openai
import cv2
im=cv2.imread("dog.jpg", cv2.IMREAD_UNCHANGED)
h, w, c=im.shape
s=min(h,w)
print(h, ',', w, ',s=',s)
#圖片裁切成正方形切
if w<=h:
    im=im[(h-w)//2:w+(h-w)//2, :, :]
else:
    im=im[:, (w-h)//2:h+(w-h)//2, :]
im.shape
im=cv2.resize(im, (1024, 1024))
cv2.imwrite('shiba_crop.png', im)
# mouse callback function 做法與C++塗鴉類似
def onMouse(event, x, y, flags, im):
    if event == cv2.EVENT_LBUTTONDOWN:
        flags = 1
    elif event == cv2.EVENT_MOUSEMOVE:
        if flags==1:
            cv2.circle(im,(x,y), 10, (255,255,255,0),-1)
    elif event == cv2.EVENT_LBUTTONUP:
        flags = -1
    cv2.imshow('image',im)
im=cv2.cvtColor(im, cv2.COLOR_BGR2BGRA)
cv2.namedWindow('image')
flags=-1
cv2.setMouseCallback('image', onMouse, im)
cv2.waitKey(0)
cv2.destroyWindow('image')
cv2.imwrite('mask.png', im)

im=cv2.imread("mask.png", cv2.IMREAD_UNCHANGED)
im=cv2.resize(im, (1024, 1024))
============================================= 
下面為openai dall-e api 處理:
import openai

openai.api_key_path = "openai-key.txt"

p_str="The dog plays a  red toy car in the realistic style"

r = openai.Image.create_edit(
  image=open("shiba_crop.png", "rb"),
  mask=open("mask.png", "rb"),
  prompt=p_str,
  n=1,
  size="1024x1024"
)
print(r)

im=r["data"][0]["url"]

import requests

r0 = requests.get(im)
if r0.status_code==200:
    with open('im/'+p_str+'.png', 'wb') as f:
        f.write(r0.content)

x=cv2.imread('im/'+p_str+'.png')
cv2.imshow('AI image', x)
cv2.waitKey(0)
cv2.destroyAllWindows()
 

沒有留言:

張貼留言

HTML 編輯器