pythonnumpypython-imaging-libraryphoto

Trying to make code that will get two photos turn them into arrays add them together then divide that by 2 and then make a photo with the array


import numpy as np
from PIL import Image


image1 = Image.open(
    "img1")

image2 = Image.open(
    "img2")

array1 = np.asarray(image1)


array2 = np.asarray(image2)


add = np.add(array1, array2)


divi = 2


output = np.divide(add, divi)
final_product = output.astype(int)


Image.fromarray(final_product).save("my.img.numpy.png")

Whenever I run this I get the error

TypeError: Cannot handle this data type: (1, 1, 3), <i8

the problem occurs on line 29

FYI

  1. Stackflow would not let me format this as code for some reason. 2.I am new to python and numpy

Solution

  • It's as simple as to change

    final_product = output.astype(int)
    

    to

    final_product = output.astype(np.uint8)
    

    np.uint8 is the correct dtype of an array that came from an image. When you operate a division to the array the dtype changes to float64

    You can check the dtype of a numpy array like this:

    print(arr.dtype)
    

    Cheers!