"AttributeError: 'PixelAccess' object has no attribute 'mode'" when merging image

Viewed 167

I'm learning in an academic course python 3 and we currently study this PIL library. in a certain task I need to take a couple of images and to run some tests on them, and one of the tests is to merge a gray image to an RGB image using Image.merge(). I have copied the part which is relevant to my problem here but I might be wrong and copied too little:

imag1= Image.open(im1_file)
imag2= Image.open(im2_file)


# convert the images to grayscale
img1 = imag1.convert('L')
img2 = imag2.convert('L')
# calculate the images histograms
mat1= img1.load()
mat2= img2.load()
hist1= img1.histogram()
hist2= img2.histogram()


# creat lists for bright pixels in the images
hist1count= hist1[128:]
hist2count= hist2[128:]
sum1= sum(hist1count)
sum2= sum(hist2count)

# calculate the mean brightness for each image in those bright pixels
mean1= sum1/len(hist1count)
mean2 =sum2/len(hist2count)

# compare images total number of bright pixels and assign the image
if sum1 > sum2:
    mat_saved= mat1
    img_saved= img1
elif sum2 > sum1:
    mat_saved= mat2
    img_saved= img2
# and the mean brightness of the image with the larger amount of bright pixels to variables for later use
if mean1 >  mean2:
    rmean_saved= mean1
elif mean2> mean1:
    rmean_saved= mean2
else:
    r_mean_saved = Image.new('L', (w,h), 0)


# creat image for the new red channel in the output image
new_img = img_saved.copy()
w, h=new_img.size
new_mat = new_img.load()

# creat a red rectangle border to the selected output image
for x in range(w):
    for y in range(h):
        new_mat[x,0]= rmean_saved
        new_mat[x, h-1]= rmean_saved
        new_mat[0, y]= rmean_saved
        new_mat[w-1, y]= rmean_saved

# merge the red channel image with blue and green channel images to creat the output image
img_mixed= Image.merge("RGB", (new_mat  ,mat_saved , mat_saved))

It gives me back an error which says:

Traceback (most recent call last):
File "./Root/src/main.py", line 103, in c,selected_image,marked_img = compare_and_mark_images(im1_file,im2_file)
File "./Root/src/main.py", line 89, in compare_and_mark_images img_mixed= Image.merge("RGB", (new_mat ,mat_saved , mat_saved))
File "/usr/lib/python3/dist-packages/PIL/Image.py", line 2118, in merge if im.mode != getmodetype(mode):
AttributeError: 'PixelAccess' object has no attribute 'mode

Note: I think the code works fine from small tests I've done during writing, the problem starts in the last line, the merge() function.

0 Answers
Related