AP Prep


In the Blog add notes and observations on each code cell that request an answer.

code block 2

  • A list of image dictionaries is produced by the image data() function after it has prepared a number of images.
  • scale image() resizes a PIL image to 320 pixels in width and returns the result.
  • image to base64() transforms a PIL image into its base64 equivalent.
  • Image management() sets an image's properties and scales and base64-encodes it.
  • The image management add html grey() function converts an image to grayscale and adds it as HTML.
  • If name equals "main," it is determined whether the script is being imported or run directly.
  • each image in the images list's meta information, scaled view, and grayscale are shown.

code block 3

  • The program defines a class called Image Data that contains methods for manipulating images and image data.
  • The source, label, file, path, and baseWidth attributes are initialized on creation of the object by the Image Data constructor.
  • An image is scaled to the necessary width using the scale image() function.
  • A PIL picture is transformed into base64 HTML code using the image to html() method.
  • A PIL picture is turned into grayscale using the image to html grey() technique.
  • A series of photographs are prepared using the image data() method, which then returns the path and the images.
  • For each image, the image objects() function produces an object of Image Data and returns a list of those objects.
  • Each image object's information, scaled image, and grayscale image are printed in the if name == "main": section.

In blog add College Board practice problems for 2.2

Numpy, manipulating pixels.

import numpy as np
from PIL import Image

# load the image and convert to a Numpy array
img = Image.open("image.png")
img_arr = np.array(img)

# define a function to manipulate the image by a certain color channel
def manipulate_color_channel(img_arr, color_channel, intensity):
    # copy the original array to avoid modifying it directly
    manipulated_arr = img_arr.copy()
    # index the color channel and multiply by the desired intensity
    manipulated_arr[:, :, color_channel] *= intensity
    # make sure the pixel values are within the valid range of 0-255
    manipulated_arr = np.clip(manipulated_arr, 0, 255)
    # convert the array back to an image
    manipulated_img = Image.fromarray(manipulated_arr.astype(np.uint8))
    return manipulated_img

# manipulate the image using the red color channel
manipulated_img = manipulate_color_channel(img_arr, 0, 2)
manipulated_img.show()

# manipulate the image using the green color channel
manipulated_img = manipulate_color_channel(img_arr, 1, 1.5)
manipulated_img.show()

# manipulate the image using the blue color channel
manipulated_img = manipulate_color_channel(img_arr, 2, 0.5)
manipulated_img.show()

Binary and Hexadecimal reports

import cv2
import numpy as np

# Read the image in grayscale
img = cv2.imread('example.jpg', cv2.IMREAD_GRAYSCALE)

# Convert to red scale
red_img = np.zeros_like(img)
red_img[:, :, 0] = img

# Display pixel values in binary and hexadecimal formats
for i in range(10):
    for j in range(10):
        pixel_value = red_img[i, j]
        binary_value = '{0:b}'.format(pixel_value)
        hex_value = '{0:x}'.format(pixel_value)
        print(f"Pixel value: {pixel_value}, Binary value: {binary_value}, Hex value: {hex_value}")

Compression and Sizing of images.

from PIL import Image

# Open the original image
img = Image.open('original_image.jpg')

# Save the image in PNG format with maximum compression
img.save('compressed_image.png', optimize=True, compress_level=9)

Blur the image or write Meta Data on screen, aka Title, Author and Image size.

from PIL import Image, ImageDraw, ImageFont, ImageFilter

class ImageEditor:
    def __init__(self, file_path):
        self.image = Image.open(file_path)
        self.width, self.height = self.image.size

    def blur(self, radius=10):
        self.image = self.image.filter(ImageFilter.GaussianBlur(radius))

    def add_meta_data(self, title, author):
        font = ImageFont.truetype('arial.ttf', size=20)
        draw = ImageDraw.Draw(self.image)
        draw.text((10, 10), f'Title: {title}', font=font, fill='white')
        draw.text((10, 40), f'Author: {author}', font=font, fill='white')
        draw.text((10, self.height - 30), f'Image size: {self.width} x {self.height}', font=font, fill='white')

    def save_image(self, file_path):
        self.image.save(file_path)

# Example usage
editor = ImageEditor('example_image.jpg')
editor.blur(radius=15)
editor.add_meta_data('Beautiful Scenery', 'John Doe')
editor.save_image('edited_image.jpg')

2.3 Hacks

Code Block 1:

print(df[['GPA']])

print()

print(df[['Student ID','GPA']].to_string(index=False))

Code Block 2:

print(df.sort_values(by=['GPA']))


print()

print(df.sort_values(by=['GPA'], ascending=False))

Code Block 3:

print(df[df.GPA > 3.00])

This code filters the rows of the original DataFrame 'df' where the value of the 'GPA' column is greater than 3.00, and prints the resulting filtered DataFrame. In other words, it selects and displays all rows where the value in the 'GPA' column is greater than 3.00.


Code Block 4:

print(df[df.GPA == df.GPA.max()])

print()


print(df[df.GPA == df.GPA.min()])

Code Block 5:

import pandas as pd

dict = {
  "calories": [420, 380, 390],
  "duration": [50, 40, 45]
}


print("-------------Dict_to_DF------------------")
df = pd.DataFrame(dict)
print(df)


print("----------Dict_to_DF_labels--------------")
df = pd.DataFrame(dict, index = ["day1", "day2", "day3"])
print(df)

Code Block 6

print("-------Examine Selected Rows---------")


print(df.loc[["day1", "day3"]])


print("--------Examine Single Row-----------")
print(df.loc["day1"])

Code Block 7

import pandas as pd

df = pd.read_csv('files/data.csv').sort_values(by=['Duration'], ascending=False)

print("--Duration Top 10---------")
print(df.head(10))

print("--Duration Bottom 10------")
print(df.tail(10))

Code Block 8:

import pandas as pd
import requests

def fetch():
    '''Obtain data from an endpoint'''
    url = "https://flask.nighthawkcodingsociety.com/api/covid/"
    fetch = requests.get(url)
    json = fetch.json()

    # filter data for requirement
    df = pd.DataFrame(json['countries_stat'])  # filter endpoint for country stats
    print(df.loc[0:5, 'country_name':'deaths']) # show row 0 through 5 and columns country_name through deaths
    
fetch()

Create or Find your own dataset

import json

json_str = '''
{
    "houses": [
        {
            "id": 1,
            "location": "Los Angeles",
            "bedrooms": 3,
            "bathrooms": 2,
            "square_feet": 1800,
            "price": 950000
        },
        {
            "id": 2,
            "location": "San Francisco",
            "bedrooms": 2,
            "bathrooms": 1,
            "square_feet": 1200,
            "price": 1200000
        },
        {
            "id": 3,
            "location": "New York City",
            "bedrooms": 4,
            "bathrooms": 3,
            "square_feet": 2500,
            "price": 1800000
        },
        {
            "id": 4,
            "location": "Chicago",
            "bedrooms": 3,
            "bathrooms": 2,
            "square_feet": 2000,
            "price": 700000
        },
        {
            "id": 5,
            "location": "Seattle",
            "bedrooms": 5,
            "bathrooms": 3,
            "square_feet": 3000,
            "price": 2200000
        },
        {
            "id": 6,
            "location": "Boston",
            "bedrooms": 2,
            "bathrooms": 1,
            "square_feet": 1000,
            "price": 750000
        },
        {
            "id": 7,
            "location": "Austin",
            "bedrooms": 4,
            "bathrooms": 2,
            "square_feet": 2200,
            "price": 900000
        },
        {
            "id": 8,
            "location": "Denver",
            "bedrooms": 3,
            "bathrooms": 2,
            "square_feet": 1900,
            "price": 650000
        },
        {
            "id": 9,
            "location": "Miami",
            "bedrooms": 2,
            "bathrooms": 1,
            "square_feet": 1100,
            "price": 550000
        },
        {
            "id": 10,
            "location": "Portland",
            "bedrooms": 4,
            "bathrooms": 2,
            "square_feet": 2400,
            "price": 1100000
        }
    ]
}
'''

data = json.loads(json_str)