Reputation: 1954
I am learning to use numpy to manipulate images, but the color information was missing. I would like to find out why this happen.
My goal is to extract the difference between two images.
Zero step: Load library
import numpy as np
from PIL import Image
First step: Vectorize image with RGBA information
img_org = Image.open('lena.png').convert('RGBA')
arr_org = np.array(img_org)
img_mod = Image.open('lena_modified.png').convert('RGBA')
arr_mod = np.array(img_mod)
arr_diff= np.zeros_like(arr_mod)
Second step: Find out the difference between two images by logic rule
for i in range(arr_mod.shape[0]) :
for j in range(arr_mod.shape[1]) :
if np.all(arr_mod[i, j]) == np.all(arr_org[i, j]):
arr_diff[i,j] = (0,0,0,0)
else :
arr_diff[i, j] = arr_mod[i, j]
Third step: Switch the image RGBA information back to image
img_diff = Image.fromarray(arr_diff, 'RGBA')
img_diff.save('ans_two.png')
I hope to get colorful Welly from the modified Lena image. Like this
However, I have no idea it only detect the outline/black part of the image. Any possible reason for this?
Disclaimer: This was a homework from a course offered in NTU during 2017 Spring. I am following this course and learn by myself. So you are NOT doing homework for me or anyone else. Thank you!
Upvotes: 0
Views: 265
Reputation: 1954
Let me explain my mistake in more details. Just as @Abhijith pk explanation, np.all
is not for comparing array value (here is pixel value). It is for checking whether all the value in the array is True.
For example, I check the bottom right corner arr_org[511,511]=[ 75 18 18 255]
& np.all([ 75 18 18 255])=True
means none of the RGBA element is zero.
However, for the black outline, its RGBA will be [ 0 0 0 255]
& np.all([0 0 0 255])=False
means some of the RGBA element is zero.
I am using the wrong code but I get the outline coincidentally. It is because in the original Lena image, most/all of the RGBA pixel values are nonzero and np.all = True
; while in the modified Lena image, the outline of Welly is black and has zeros in RGBA pixel values np.all = False
. Since only the black outline has false
output from np.all
, I am lucky to get the outline by comparing np.all
.
Again, using np.all
is wrong for my case. Using np.array_equal
is suggested. I am just trying to analyze the coincidence of getting black outline.
Upvotes: 0
Reputation: 4059
Modifying your RGB comparison should fix this:
if np.array_equal(arr_mod[i, j],arr_org[i, j]):
arr_diff[i,j] = (0,0,0,0)
else :
arr_diff[i, j] = arr_mod[i, j]
The issue is because np.all will return True if all values are True or their Truthiness value is true,the below example will return true in the interactive console
np.all([2,3,4,5]) == np.all([1,2,3,4])
This will return false in interactive console:
np.all([2,3,4,5]) == np.all([0,2,3,4])
Upvotes: 1