0

I don't know what's wrong and why nothing worked for me. The picture is 500x500.

I tried using arrays and loops but It didn't work out. My code

from PIL import Image

picture_resized = picture.resize( (500,500) )

im = np.array(Image.open('Lenna.png').convert('RGB'))

Image.fromarray(im).save('result.png')

im[0::2,0::2] = [0,0,0]
im[0::3,0::3] = [0,0,0]

%matplotlib notebook
plt.imshow(picture_resized)
Flow
  • 551
  • 1
  • 3
  • 9
mahmut
  • 1
  • 1
  • Please clarify what did not work out for you. The lines `im[0::2,0::2] = [0,0,0]` and `im[0::3,0::3] = [0,0,0]` seem for me to do exactly what you want. Your provided code however saves an image before you do the desired processing and is showing (`plt.imshow`) `picture_resized`, which is also not processed for having black pixels. – Flow Nov 29 '22 at 08:29

1 Answers1

0

You're close! This should do what you want:

import numpy as np
from PIL import Image

# Load image and make into Numpy array
im = np.array(Image.open('artistic-swirl.jpg'))

# Make every second element on x-axis black
im[:, 0::2] = [0,0,0]

# Make every third element on y-axis black
im[::3, :] = [0,0,0]

Note: You should read a colon (:) as meaning "all columns" or "all rows" depending on whether it is specified for the first or second axis.

Turns this:

enter image description here

into this:

enter image description here

If you are using Jupyter, based off your question, you'll need to add something like this at the end to actually display the result.

%matplotlib notebook
plt.imshow(im)

Or, if you want to save a PNG with PIL, you can use:

im.save('result.png')
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
  • This code below did the job, but it opens up as an image from the pc but it doesnt load below the code, it shouldn't manually open me the image I got from that code,that's weird. import numpy as np from PIL import Image im = np.array(Image.open('Lenna.png')) im[:, 0::2] = [0,0,0] im[::3, :] = [0,0,0] Image.fromarray(im).show ('result.png') – mahmut Nov 29 '22 at 15:59
  • I don't understand your comment, sorry. It's hard to read code in comments. Also, there is no punctuation. Maybe any issues are caused by using a PNG which may be indexed. See https://stackoverflow.com/a/52307690/2836621 Try adding `.convert('RGB')` to the end of the line in which you do `Image.open()`. I didn't need that as I used a JPEG. – Mark Setchell Nov 29 '22 at 16:21
  • I just want my image to show up under my code the print command didnt work, I dont need to open it up just to show up underneath my code, like 2 images you just uploaded above. The code did the work but I need my image to show up. – mahmut Nov 29 '22 at 17:31
  • I'm still unsure what the issue is, but have updated my answer near the end. – Mark Setchell Nov 29 '22 at 17:37