OpenAI + OpenCV
3 min readJun 19, 2023
idea: describe an image processing problem to OpenAI → receive code → run
Write a python function that inputs an image and returns a darker version of it.
import numpy as np
from PIL import Image
# Function takes a image as input and returns a darker version of it
def make_darker(input_image):
#convert the image to a numpy array
arr = np.array(input_image)
#find the shape of the array
shape = arr.shape
#create an empty array of the same size
darker_arr = np.empty(shape, dtype='uint8')
# loop through and subtract 15 from each element in order to make the image darker
for row in range(shape[0]):
for col in range(shape[1]):
darker_arr[row][col] = arr[row][col] - 15
# return the darker image
return Image.fromarray(darker_arr)
prompt = """"Write a python function named runme_001
that inputs an image as a numpy array
and uses opencv vector functions
to return a darker version of the input image
without running a for loop on the pixels.
"""
import cv2
import numpy as np
def runme_001(img):
# Create a new image with lower intensity
dark_img = cv2.add(img, np.array([-50.0]))
# re-scale the pixel
dark_img = cv2.normalize(dark_img, None, 0, 255, cv2.NORM_MINMAX)
return dark_img
import cv2
import numpy as np
def runme_001(src):
# Create a darkening mask
mask = np.ones(src.shape, dtype="uint8") * 75
# Apply the mask with the multiply function from opencv
res = cv2.multiply(src, mask)
return res
def runme_001(image):
#import opencv and numpy libraries
import cv2, numpy as np
#apply the addWeight function to make it darker
result = cv2.addWeighted(image, 0.75, np.zeros(image.shape, image.dtype), 0, 0)
#return the result (darker version of the input image)
return result
input: an image as a numpy array
uses: opencv vector functions
return: darker version of the input image
conditions: without running a for loop on the pixels.
Next: refactor as a class + bash interface.