Hanif Abdillah
Hanif Abdillah

Reputation: 43

How to Create New Image From Array List Which Contains Binary Pixel Data

Here I use the PIL Library to read and manipulate images. I am confused, how to create a new image from the list of arrays containing binary pixel data, after being converted to binary images.

I have tried it, but the resulting image is of type RGB, not a binary image. The following is the code that I wrote:

from PIL import Image
import numpy as np

img = Image.open('data_train/ga.jpeg')

pixels = img.load()

width, height = img.size

all_pixels = []

for x in range(width):

    for y in range(height):
        hpixel = pixels[x, y]
        img_gray = (0.2989 * hpixel[0]) + (0.5870 * hpixel[1]) + (0.1140 * hpixel[2])

        if img_gray >= 110:
            all_pixels.append('1')
        else:
            all_pixels.append('0')

data_isi = {'0': 0,

            '1': 255}

data = [data_isi[letter] for letter in all_pixels]

img_new = Image.fromarray(data)

img_new.save('data_train/gabiner.jpeg')

Upvotes: 1

Views: 1043

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207345

Updated Answer

As you are required to use a for loop, you could go with something more like this:

#!/usr/bin/env python3

from PIL import Image

# Load image and get dimensions
img = Image.open('start.jpg').convert('RGB')
width, height = img.size

# Actually load input pixels, else PIL is too lazy
imi = img.load()

# List of result pixels
imo = []

for y in range(height):
    for x in range(width):
        R, G, B = imi[x, y]
        gray = (0.2989 * R) + (0.5870 * G) + (0.1140 * B)

        if gray >= 110:
            imo.append(255)
        else:
            imo.append(0)

# Make output image and put output pixels into it
result = Image.new('L', (width,height))
result.putdata(imo)

# Save result
result.save('result.png')

Which turns this start image:

enter image description here

Into this result:

enter image description here

Original Answer

You appear to be converting the image to greyscale and thresholding at 110, which can be done much more simply, and faster, like this:

#!/usr/local/bin/python3

from PIL import Image

# Load image and make greyscale
im = Image.open('image.png').convert('L')

# Threshold to make black and white
thr = im.point(lambda p: p > 110 and 255)

# Save result
thr.save('result.png')

Upvotes: 1

Related Questions