If you like DNray Forum, you can support it by - BTC: bc1qppjcl3c2cyjazy6lepmrv3fh6ke9mxs7zpfky0 , TRC20 and more...

 

Python Grayscale Conversion without Loops

Started by solomankane, Oct 24, 2024, 01:10 AM

Previous topic - Next topic

solomankaneTopic starter

Using numpy, without Python loops, convert a color image to black and white in Python using the formula:

C = 0.2989 * R + 0.5870 * G + 0.1140 * B It is believed that the color calculated in this way is best suited for the human eye, since the eye perceives the brightness of each component differently.

Input format The folder with your solution will contain the image.jpg file with the original image. Output format Save the result to the res.jpg file in the current folder. Notes Remember that the value of each color component is an integer, so the result must be rounded. To do this, use the round() method.
  •  


mit_searchonic

To convert a color image to black and white, we can use NumPy's array operations to apply the given formula to each pixel. First, we load the image using OpenCV and convert it to a NumPy array. Then, we create a new array to store the grayscale values and apply the formula to each pixel. The result is a grayscale image, which we can save to a new file. Here's the code snippet:

import cv2
import numpy as np

# Load the image
img = cv2.imread('image.jpg')

# Convert to grayscale using the given formula
gray = np.zeros((img.shape
[o], img.shape[1]), dtype=np.uint8)
gray[:] = np.round(0.2989 * img[:, :, 0] + 0.5870 * img[:, :, 1] + 0.1140 * img[:, :, 2])

# Save the result
cv2.imwrite('res.jpg', gray)
  •  

djnoslee

you can also achieve this by:

Unpacking the wxhx3 image into a (w*h)x3 matrix, a.k.a. 'flattening the data'
Multiplying the matrix by the vector of weights-coefficients (3x1), resulting in a (w*h)x1 vector, aka 'ectorization'
Packing the vector back into a wxh image, a.k.a. 'eshaping the data'

In Python, we can use NumPy to simplify this process:

import numpy as np
from PIL import Image

img = Image.open('image.jpg')
arr = np.asarray(img, dtype='uint8')
k = np.array([0.2989, 0.587, 0.114])  # weights-coefficients
w, h, _ = arr.shape
arr = arr.reshape((w*h, 3))  # flatten data
out = np.dot(arr, k)  # vectorization
out = out.reshape((w, h))  # reshape data
img2 = Image.fromarray(out.astype(np.uint8))
img2.save('result_bw.png')

The sum of the multiplication is indeed the scalar product of vectors. In this code, we're using NumPy's dot function to perform the matrix multiplication, which is equivalent to the np.matmul function.
  •  

donaldselby

I tackled the task using a flowchart approach, which required me to dig deep into the dоcumentation. I utilized the xlsxwriter library to create an Excel file. Here's a breakdown of how I processed the input data and generated the spreadsheet:

import xlsxwriter
import sys

# Read input data and clean it
data_entries = list(map(str.strip, sys.stdin))

# Initialize a new workbook and worksheet
workbook = xlsxwriter.Workbook('output.xlsx')
sheet = workbook.add_worksheet()

# Transform the input data into tuples of items and prices
data_tuples = [tuple(entry.split()) for entry in data_entries]

# Populate the worksheet with the item names and their corresponding prices
for index, (item_name, item_price) in enumerate(data_tuples):
    sheet.write(index, 0, item_name)
    sheet.write(index, 1, int(item_price))

# Create a pie chart to visualize the data
pie_chart = workbook.add_chart({'type': 'pie'})
pie_chart.add_series({
    'values': '=Sheet1!B1:B5',
    'categories': '=Sheet1!A1:A5'
})

# Insert the chart into the worksheet
sheet.insert_chart('C3', pie_chart)

# Save and close the workbook
workbook.close()

In this script, I first read the input data from the standard input, ensuring to strip any extra whitespace. After initializing the workbook and worksheet, I processed the data into a list of tuples for easier manipulation. I then populated the worksheet with the item names and their respective prices. Finally, I constructed a pie chart to provide a visual representation of the data, which I inserted into the worksheet before closing the workbook. This approach not only streamlined the data handling but also enhanced the overall output presentation.
  •  


If you like DNray forum, you can support it by - BTC: bc1qppjcl3c2cyjazy6lepmrv3fh6ke9mxs7zpfky0 , TRC20 and more...