Skip to content
This repository was archived by the owner on Jun 29, 2024. It is now read-only.

Internship completed #59

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions PADALA AKHIL NANDU YADAV/Readme.md.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
Advance Level

Task 1 :Image Converter:

Where the program that accepts images in multiple formats that may be in JPEG, PNG, BMP, GIF and converts them into a desired format using Python Imaging Library (PIL) that may be any of the formats mentioned.

Task 2:Data Analysis with Pandas:

In the program on loading the "Iris" dataset from Seaborn and analyzing it using Pandas and performed exploratory data analysis, cleaning, aggregation, visualizations, and correlation calculations. The output of the program will consits of calculations , graph which will be more understanding to users.

Task 3:Linear Regression with Scikit-learn:

Completed a program by applying linear regression to predict house prices from the Boston housing dataset using scikit-learn and compared train and test scores and plot residuals.

Task 4:Image Compression:

Developed a Python program for compressing images while maintaining quality by exploring compression techniques like RLE and DCT and allowing users to adjust compression quality, support various image formats, and provide output options. Optionally, include a user interface.
33 changes: 33 additions & 0 deletions PADALA AKHIL NANDU YADAV/Task1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
from PIL import Image
import os

def convert_image(input_path, output_path, output_format):
try:
# Open the image
with Image.open(input_path) as img:
# Convert and save the image to the desired format
img.save(output_path, format=output_format)
print(f"Image converted successfully to {output_format} format.")
except Exception as e:
print(f"An error occurred: {e}")

def main():
input_path = input("Enter the path to the input image: ").strip('"')
output_format = input("Enter the desired output format (e.g., JPEG, PNG, BMP, GIF): ").upper()

# Validate output format
if output_format not in ['JPEG', 'PNG', 'BMP', 'GIF']:
print("Invalid output format. Please choose from JPEG, PNG, BMP, or GIF.")
return

# Extract the file name and directory
file_name, file_extension = os.path.splitext(os.path.basename(input_path))

# Set the output path
output_path = os.path.join(os.path.dirname(input_path), f"{file_name}_converted.{output_format.lower()}")

# Convert the image
convert_image(input_path, output_path, output_format)

if __name__ == "__main__":
main()
35 changes: 35 additions & 0 deletions PADALA AKHIL NANDU YADAV/Task2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#1. Load the DataSet:
import seaborn as sns
iris_df = sns.load_dataset('iris')

#2. Exploratory Data Analysis (EDA):

print(iris_df.info())
print(iris_df.describe())
print(iris_df.head())

#3. Data Cleaning:

print(iris_df.isnull().sum())
print(iris_df.duplicated().sum())

#4. Aggregation:

species_mean = iris_df.groupby('species').mean()

iris_df["species"] = iris_df["species"].map({"setosa":0,"virginica":1})

#5. Visualizations:

import matplotlib.pyplot as plt
import seaborn as sns

sns.pairplot(iris_df, hue='species')
plt.show()

sns.heatmap(iris_df.corr(), annot=True, cmap='coolwarm')
plt.show()

#6. Correlation Calculations:

correlation_matrix = iris_df.corr()
45 changes: 45 additions & 0 deletions PADALA AKHIL NANDU YADAV/Task3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
import pandas as pd
data_url = "https://archive.ics.uci.edu/ml/machine-learning-databases/housing/housing.data"
raw_df = pd.read_csv(data_url, sep="\s+", skiprows=22, header=None)
data = np.hstack([raw_df.values[::2, :], raw_df.values[1::2, :2]])
target = raw_df.values[1::2, 2]

# Load the Boston housing dataset

X = data
y = target

# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Initialize the linear regression model
model = LinearRegression()

# Fit the model on the training data
model.fit(X_train, y_train)

# Predict on the training and testing data
y_train_pred = model.predict(X_train)
y_test_pred = model.predict(X_test)

# Calculate the scores
train_score = model.score(X_train, y_train)
test_score = model.score(X_test, y_test)

print("Training score:", train_score)
print("Testing score:", test_score)

# Plot residuals
plt.scatter(y_train_pred, y_train_pred - y_train, c='blue', marker='o', label='Training data')
plt.scatter(y_test_pred, y_test_pred - y_test, c='lightgreen', marker='s', label='Testing data')
plt.xlabel('Predicted values')
plt.ylabel('Residuals')
plt.legend(loc='upper left')
plt.hlines(y=0, xmin=0, xmax=50, lw=2, color='red')
plt.title('Residual plot')
plt.show()
59 changes: 59 additions & 0 deletions PADALA AKHIL NANDU YADAV/Task4.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
from PIL import Image
import os

def get_size_format(b, factor=1024, suffix="B"):
"""
Scale bytes to its proper byte format.
e.g: 1253656 => '1.20MB', 1253656678 => '1.17GB'
"""
for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]:
if b < factor:
return f"{b:.2f}{unit}{suffix}"
b /= factor
return f"{b:.2f}Y{suffix}"

def compress_img(image_name, new_size_ratio=0.9, quality=90, width=None, height=None, to_jpg=True):
# Print the file path for debugging
print(f"[*] Attempting to open file: {image_name}")

# Load the image into memory
img = Image.open(image_name)

# Print the original image shape
print("[*] Image shape:", img.size)

# Get the original image size in bytes
image_size = os.path.getsize(image_name)
print("[*] Size before compression:", get_size_format(image_size))

if new_size_ratio < 1.0:
# If resizing ratio is below 1.0, multiply width & height with this ratio to reduce image size
img = img.resize((int(img.size[0] * new_size_ratio), int(img.size[1] * new_size_ratio)), Image.LANCZOS)
elif width and height:
# If width and height are set, resize with them instead
img = img.resize((width, height), Image.LANCZOS)

# Split the filename and extension
filename, ext = os.path.splitext(image_name)

# Convert RGBA to RGB if saving as JPEG
if to_jpg and img.mode == 'RGBA':
img = img.convert('RGB')

# Make a new filename appending "_compressed" to the original file name
if to_jpg:
# Change the extension to JPEG
new_filename = f"{filename}_compressed.jpg"
else:
# Retain the same extension of the original image
new_filename = f"{filename}_compressed{ext}"

# Save the compressed image
img.save(new_filename, optimize=True, quality=quality)

# Print the new image shape
print("[+] New Image shape:", img.size)
print(f"[*] Compressed image saved as: {new_filename}")

# Example usage:
compress_img(r"C:\Users\sarayu sree\Pictures\Picture1.png", new_size_ratio=0.8, quality=80, width=800, height=600)