Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Jun 29, 2024. It is now read-only.

Commit 104abd2

Browse files
Merge pull request #11 from Aswini147/main
Advanced Level
2 parents 56130f8 + b743bfa commit 104abd2

File tree

4 files changed

+176
-0
lines changed

4 files changed

+176
-0
lines changed

‎Naga Tejaswini Nandyala/Task1

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
from PIL import Image
2+
import os
3+
4+
def convert_image(input_path, output_path, output_format):
5+
try:
6+
# Open the image
7+
with Image.open(input_path) as img:
8+
# Convert and save the image to the desired format
9+
img.save(output_path, format=output_format)
10+
print(f"Image converted successfully to {output_format} format.")
11+
except Exception as e:
12+
print(f"An error occurred: {e}")
13+
14+
def main():
15+
input_path = input("Enter the path to the input image: ")
16+
output_format = input("Enter the desired output format (e.g., JPEG, PNG, BMP, GIF): ").upper()
17+
18+
# Validate output format
19+
if output_format not in ['JPEG', 'PNG', 'BMP', 'GIF']:
20+
print("Invalid output format. Please choose from JPEG, PNG, BMP, or GIF.")
21+
return
22+
23+
# Extract the file name and extension
24+
file_name, file_extension = os.path.splitext(input_path)
25+
26+
# If the input file already has an extension, remove it
27+
file_name_without_ext = file_name.split('.')[0]
28+
29+
# Set the output path
30+
output_path = f"{file_name_without_ext}_converted.{output_format.lower()}"
31+
32+
# Convert the image
33+
convert_image(input_path, output_path, output_format)
34+
35+
if __name__ == "__main__":
36+
main()

‎Naga Tejaswini Nandyala/Task2

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import seaborn as sns
2+
import pandas as pd
3+
import matplotlib.pyplot as plt
4+
5+
# Load the Iris dataset from Seaborn
6+
iris = sns.load_dataset("iris")
7+
numeric_iris = iris.drop(columns='species')
8+
9+
# Display the first few rows of the dataset
10+
print("First few rows of the dataset:")
11+
print(iris.head())
12+
13+
# Summary statistics
14+
print("\nSummary statistics:")
15+
print(iris.describe())
16+
17+
# Checking for missing values
18+
print("\nMissing values:")
19+
print(iris.isnull().sum())
20+
21+
# Visualizations
22+
# Pairplot
23+
sns.pairplot(iris, hue="species")
24+
plt.title("Pairplot of Iris Dataset")
25+
plt.show()
26+
27+
# Boxplot
28+
plt.figure(figsize=(10, 6))
29+
sns.boxplot(data=iris, orient="h")
30+
plt.title("Boxplot of Iris Dataset")
31+
plt.show()
32+
33+
# Histograms
34+
plt.figure(figsize=(10, 6))
35+
iris.hist()
36+
plt.suptitle("Histograms of Iris Dataset")
37+
plt.show()
38+
39+
# Correlation heatmap
40+
plt.figure(figsize=(8, 6))
41+
sns.heatmap(numeric_iris.corr(), annot=True, cmap="coolwarm")
42+
plt.title("Correlation Heatmap of Iris Dataset")
43+
plt.show()

‎Naga Tejaswini Nandyala/Task3

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import numpy as np
2+
import matplotlib.pyplot as plt
3+
from sklearn.model_selection import train_test_split
4+
from sklearn.linear_model import LinearRegression
5+
from sklearn.metrics import mean_squared_error
6+
import pandas as pd
7+
data_url = "http://lib.stat.cmu.edu/datasets/boston"
8+
raw_df = pd.read_csv(data_url, sep="\s+", skiprows=22, header=None)
9+
data = np.hstack([raw_df.values[::2, :], raw_df.values[1::2, :2]])
10+
target = raw_df.values[1::2, 2]
11+
12+
# Load the Boston housing dataset
13+
14+
X = data
15+
y = target
16+
17+
# Split the data into training and testing sets
18+
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
19+
20+
# Initialize the linear regression model
21+
model = LinearRegression()
22+
23+
# Fit the model on the training data
24+
model.fit(X_train, y_train)
25+
26+
# Predict on the training and testing data
27+
y_train_pred = model.predict(X_train)
28+
y_test_pred = model.predict(X_test)
29+
30+
# Calculate the scores
31+
train_score = model.score(X_train, y_train)
32+
test_score = model.score(X_test, y_test)
33+
34+
print("Training score:", train_score)
35+
print("Testing score:", test_score)
36+
37+
# Plot residuals
38+
plt.scatter(y_train_pred, y_train_pred - y_train, c='blue', marker='o', label='Training data')
39+
plt.scatter(y_test_pred, y_test_pred - y_test, c='lightgreen', marker='s', label='Testing data')
40+
plt.xlabel('Predicted values')
41+
plt.ylabel('Residuals')
42+
plt.legend(loc='upper left')
43+
plt.hlines(y=0, xmin=0, xmax=50, lw=2, color='red')
44+
plt.title('Residual plot')
45+
plt.show()

‎Naga Tejaswini Nandyala/Task4

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
from PIL import Image
2+
import os
3+
4+
def get_size_format(b, factor=1024, suffix="B"):
5+
"""
6+
Scale bytes to its proper byte format.
7+
e.g: 1253656 => '1.20MB', 1253656678 => '1.17GB'
8+
"""
9+
for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]:
10+
if b < factor:
11+
return f"{b:.2f}{unit}{suffix}"
12+
b /= factor
13+
return f"{b:.2f}Y{suffix}"
14+
15+
def compress_img(image_name, new_size_ratio=0.9, quality=90, width=None, height=None, to_jpg=True):
16+
# Load the image into memory
17+
img = Image.open(image_name)
18+
19+
# Print the original image shape
20+
print("[*] Image shape:", img.size)
21+
22+
# Get the original image size in bytes
23+
image_size = os.path.getsize(image_name)
24+
print("[*] Size before compression:", get_size_format(image_size))
25+
26+
if new_size_ratio < 1.0:
27+
# If resizing ratio is below 1.0, multiply width & height with this ratio to reduce image size
28+
img = img.resize((int(img.size[0] * new_size_ratio), int(img.size[1] * new_size_ratio)), Image.ANTIALIAS)
29+
elif width and height:
30+
# If width and height are set, resize with them instead
31+
img = img.resize((width, height), Image.ANTIALIAS)
32+
33+
# Split the filename and extension
34+
filename, ext = os.path.splitext(image_name)
35+
36+
# Make a new filename appending "_compressed" to the original file name
37+
if to_jpg:
38+
# Change the extension to JPEG
39+
new_filename = f"{filename}_compressed.jpg"
40+
else:
41+
# Retain the same extension of the original image
42+
new_filename = f"{filename}_compressed{ext}"
43+
44+
# Save the compressed image
45+
img.save(new_filename, optimize=True, quality=quality)
46+
47+
# Print the new image shape
48+
print("[+] New Image shape:", img.size)
49+
print(f"[*] Compressed image saved as: {new_filename}")
50+
51+
# Example usage:
52+
compress_img("wp1966999.jpg", new_size_ratio=0.8, quality=80, width=800, height=600)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /