Популярное

Музыка Кино и Анимация Автомобили Животные Спорт Путешествия Игры Юмор

Интересные видео

2025 Сериалы Трейлеры Новости Как сделать Видеоуроки Diy своими руками

Топ запросов

смотреть а4 schoolboy runaway турецкий сериал смотреть мультфильмы эдисон
dTub
Скачать

Why Does Pillow's .convert('L') Not Modify Images In-Place and How to Get a 2D Grayscale Numpy Arra

Автор: vlogommentary

Загружено: 2025-12-23

Просмотров: 0

Описание:

Learn why Pillow's image conversion methods return new images instead of modifying in-place, and how to properly convert images to grayscale or black & white before converting to numpy arrays.
---
This video is based on the question https://stackoverflow.com/q/79477454/ asked by the user 'Sun Bear' ( https://stackoverflow.com/u/5722359/ ) and on the answer https://stackoverflow.com/a/79477513/ provided by the user 'chrslg' ( https://stackoverflow.com/u/20037042/ ) at 'Stack Overflow' website. Thanks to these great users and Stackexchange community for their contributions.

Visit these links for original content and any more details, such as alternate solutions, latest updates/developments on topic, comments, revision history etc. For example, the original title of the Question was: Why is the greyscale & B&W images created by Pillow giving a numpy.ndarray that has a 3D shape?

Also, Content (except music) licensed under CC BY-SA https://meta.stackexchange.com/help/l...
The original Question post is licensed under the 'CC BY-SA 4.0' ( https://creativecommons.org/licenses/... ) license, and the original Answer post is licensed under the 'CC BY-SA 4.0' ( https://creativecommons.org/licenses/... ) license.

If anything seems off to you, please feel free to drop me a comment under this video.
---
Understanding Pillow’s .convert() Behavior

When working with Pillow (PIL) to convert images to grayscale or black & white, a common pitfall is expecting .convert() to change the original image object directly.

The Core Issue

Pillow's Image.convert() method does not modify the original image. Instead, it returns a new image object with the requested mode. If you call img.convert('L') without capturing the result, the original image remains unchanged.

Example mistake:

[[See Video to Reveal this Text or Code Snippet]]

Here, image_pil retains the 3-channel RGB shape because img was never replaced.

Correct Usage to Get a 2D Grayscale Numpy Array

To obtain a 2D numpy array representing a grayscale image:

Use .convert('L') and assign its result to a variable.

Convert that new image to a numpy array.

[[See Video to Reveal this Text or Code Snippet]]

What about .convert('1')?

L mode: 8-bit pixels, black and white

1 mode: 1-bit pixels, black and white, stored with 1 bit per pixel

The same principle applies: you must assign the converted image returned from .convert('1') to a variable.

Summary

Pillow's .convert() returns a new image; it does not alter the original image in-place.

Always assign the result of .convert() if you want the converted image.

Converting with .convert('L') or .convert('1') gives you single-channel images.

Converting those images to a numpy array yields a 2D array, reflecting greyscale or black & white pixels.

Correcting your code this way ensures you get the expected 2D numpy array shape instead of a 3D RGB array.

Why Does Pillow's .convert('L') Not Modify Images In-Place and How to Get a 2D Grayscale Numpy Arra

Поделиться в:

Доступные форматы для скачивания:

Скачать видео mp4

  • Информация по загрузке:

Скачать аудио mp3

Похожие видео

Код работает в 100 раз медленнее из-за ложного разделения ресурсов.

Код работает в 100 раз медленнее из-за ложного разделения ресурсов.

I Read Honey's Source Code

I Read Honey's Source Code

Самые негативные посты Stack Overflow за всю историю

Самые негативные посты Stack Overflow за всю историю

Синьор 1С: 10 привычек, без которых ты не вырастешь

Синьор 1С: 10 привычек, без которых ты не вырастешь

Typst: Современная замена Word и LaTeX, которую ждали 40 лет

Typst: Современная замена Word и LaTeX, которую ждали 40 лет

Brain rot in software development...

Brain rot in software development...

NumPy multidimensional arrays are easy! 🧊

NumPy multidimensional arrays are easy! 🧊

Срочные переговоры с Путиным / Вывод части войск

Срочные переговоры с Путиным / Вывод части войск

25 Запрещенных Гаджетов, Которые Вы Можете Купить Онлайн

25 Запрещенных Гаджетов, Которые Вы Можете Купить Онлайн

Мне потребовалось 10+ лет, чтобы понять то, что я вам расскажу через 8 минут.

Мне потребовалось 10+ лет, чтобы понять то, что я вам расскажу через 8 минут.

Microsoft begs for mercy

Microsoft begs for mercy

CLEANER Anatoly CHALLENGED BODYBUILDERS | GYM PRANK

CLEANER Anatoly CHALLENGED BODYBUILDERS | GYM PRANK

Why nobody's creating coding tutorials anymore

Why nobody's creating coding tutorials anymore

Как бы я быстро выучил Python (если бы мог начать всё сначала)

Как бы я быстро выучил Python (если бы мог начать всё сначала)

16 — Понимание цифровых изображений для обработки Python

16 — Понимание цифровых изображений для обработки Python

FFmpeg: бесплатный видеоконвертер из командной строки

FFmpeg: бесплатный видеоконвертер из командной строки

The ultimate introduction to Pillow [ Image manipulation in Python ]

The ultimate introduction to Pillow [ Image manipulation in Python ]

How exactly does binary code work? - José Américo N L F de Freitas

How exactly does binary code work? - José Américo N L F de Freitas

Чем ОПАСЕН МАХ? Разбор приложения специалистом по кибер безопасности

Чем ОПАСЕН МАХ? Разбор приложения специалистом по кибер безопасности

Сисадмины больше не нужны? Gemini настраивает Linux сервер и устанавливает cтек N8N. ЭТО ЗАКОННО?

Сисадмины больше не нужны? Gemini настраивает Linux сервер и устанавливает cтек N8N. ЭТО ЗАКОННО?

© 2025 dtub. Все права защищены.



  • Контакты
  • О нас
  • Политика конфиденциальности



Контакты для правообладателей: infodtube@gmail.com