When services use SSIM to control for quality of images do they typically select a compression setting that gives images an average SSIM of, say, 90 or do they select a different compression setting for each separate image to make each go as close to 90 as possible?
Assistant
Services that use SSIM to control the quality of images typically select a compression setting that targets a specific SSIM value for each separate image. They aim to achieve a balance between compression rate and image quality, adjusting the compression settings for each image accordingly. This way, they can make each image as close to the target SSIM value as possible while maintaining acceptable file size and visual quality. The exact target SSIM value might vary depending on the service, but the goal is generally to maintain a good balance between size and visual quality.
User
Please give me minimal yolov code to detect people. Assume i don't have weights etc installed
Assistant
To detect people using YOLOv4, you'll need a trained model and its configuration file. Here's a minimal Python code using OpenCV library to detect people using YOLOv4:
import cv2
def main():
# Load YOLOv4 model and configuration
config = 'path/to/yolov4.cfg'
weights = 'path/to/yolov4.weights'
labels_file = 'path/to/coco.names'
# Load labels
with open(labels_file, 'rt') as f:
labels = f.read().rstrip('\n').split('\n')
# Configure the network
net = cv2.dnn.readNet(weights, config)
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
# Load image
img = cv2.imread('path/to/input/image.jpg')
height, width, _ = img.shape
# Prepare input for the network
blob = cv2.dnn.blobFromImage(img, 1/255.0, (416, 416), swapRB=True, crop=False)
net.setInput(blob)
# Process output
layer_outputs = net.forward(output_layers)
# Threshold for detection
conf_threshold = 0.5
for output in layer_outputs:
for detection in output:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if labels[class_id] == "person" and confidence > conf_threshold:
center_x, center_y, w, h = (detection[0:4] * np.array([width, height, width, height])).astype(int)
x = int(center_x - w / 2)
y = int(center_y - h / 2)
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
# Display result
cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == '__main__':
main()
User
Please update this script to find images with animals and to go trough several sub folders
import os
import cv2
import shutil
from ultralytics import YOLO
for filename in os.listdir(directory):
if filename.endswith('.jpg') or filename.endswith('.png'):
# Read the image
image = cv2.imread(os.path.join(directory, filename))
# Perform object detection on the image
results = model(image)
# Check if person detections exist
if len(results) > 0:
person_class_index = 0 # Index of the "person" class
person_detections = results[0].boxes[results[0].boxes.cls == person_class_index]
# Check if any person detections were found
if len(person_detections) > 0:
print('Person detected in:', filename)
# Move the suspected image to the "possiblepeople" folder
shutil.move(os.path.join(directory, filename), os.path.join(output_directory, filename))
Assistant
To update the script to use YOLOv4 and find images containing animals while searching through subfolders, you can modify the given code as follows:
import os
import cv2
import numpy as np
import shutil
def process_directory(directory, output_directory):
for entry in os.scandir(directory):
if entry.is_dir():
process_directory(entry.path, output_directory)
elif entry.path.endswith('.jpg') or entry.path.endswith('.png'):
process_image(entry.path, output_directory)
def process_image(image_path, output_directory):
img = cv2.imread(image_path)
blob = cv2.dnn.blobFromImage(img, 1/255.0, (416, 416), swapRB=True, crop=False)
net.setInput(blob)
layer_outputs = net.forward(output_layers)
conf_threshold = 0.5
animal_detected = False
# Animal class indices in COCO dataset
animal_classes = {16, 17, 18, 19, 20, 21, 22, 23}
for output in layer_outputs:
for detection in output:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if class_id in animal_classes and confidence > conf_threshold:
animal_detected = True
break
if animal_detected:
break
if animal_detected:
print('Animal detected in:', image_path)
shutil.move(image_path, os.path.join(output_directory, os.path.basename(image_path)))
if __name__ == '__main__':
directory = 'C:/Users/Del Pin/Pexels/Animals/animals/'
output_directory = os.path.join(directory, 'contains_animals')
os.makedirs(output_directory, exist_ok=True)
config = 'path/to/yolov4.cfg'
weights = 'path/to/yolov4.weights'
net = cv2.dnn.readNet(weights, config)
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
process_directory(directory, output_directory)
User
What is the issue with this code:
import os
import cv2
import shutil
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
def detect_and_move_animals(directory):
# Create a subfolder for suspected images
output_directory = os.path.join(directory, 'possibleanimals')
os.makedirs(output_directory, exist_ok=True)
# Iterate over all files in the directory
for filename in os.listdir(directory):
if filename.endswith('.jpg') or filename.endswith('.png'):
# Read the image
image = cv2.imread(os.path.join(directory, filename))
# Perform object detection on the image
results = model(image)
# Check if animal detections exist
if len(results) > 0:
animal_class_indexes = range(14, 24) # Indexes 14 through 23 correspond to bird, cat, dog, horse, sheep, cow, elephant, bear, zebra, and giraffe
animal_detections = results[0].boxes[results[0].boxes.cls.isin(animal_class_indexes)]
# Check if any animal detections were found
if len(animal_detections) > 0:
print('Animal detected in:', filename)
# Move the suspected image to the "possibleanimals" folder
shutil.move(os.path.join(directory, filename), os.path.join(output_directory, filename))
# Close all windows
cv2.destroyAllWindows()
Assistant
The main issue with this code is that it tries to use the ultralytics package, but there is no such package. Ultralytics is a company that maintains the YOLOv5 repository, but the package name is different.
To use YOLOv5 from Ultralytics, first, you should install the yolov5 library:
User
Please use gradient descent to tweak contrast_amount until a certain mean level of haar_psi is reached. The value of contrast_amount is likely between 0.8 and 0.4
Assistant
User
This gradient descent code seems to not reach optimal values. In fact it lowers its estimates when it should be raising them:
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Replace the appropriate file paths with the actual paths of the YOLOv4 model files and the input image. Make sure you have the YOLOv4 weight files, configuration files, and class labels. You can find them in the official YOLOv4 repository.
This code requires OpenCV and NumPy installed. You can install them using pip:
pip install opencv-python
pip install numpy
After running the script, it will display the input image with rectangles drawn around detected people.
Close all windows
cv2.destroyAllWindows()
This script uses YOLOv4 and OpenCV, as previously mentioned, to detect animals in images. Make sure to update the paths to the YOLOv4 configuration and weight files.
When calling the process_directory function, it will search through the specified directory and its subdirectories for images. If it detects an animal in the image, it will move the file to the output directory. The output directory will only contain images where animals have been detected.
Path to the directory containing the images
directory = 'C:/Users/Bob/Pexels/Animals/candid/'
Call the function to detect and move animals in the images
detect_and_move_animals(directory)
pip install yolov5
Once you have installed the package, you can use the following code with the correct imports, and some modifications to work with YOLOv5:
import os
import cv2
import shutil
from yolov5 import YOLOv5 # Correct import from yolov5 library
# Load the model
model = YOLOv5("yolov5m.pt") # Change to yolov5 model and correct file name
def detect_and_move_animals(directory):
# Create a subfolder for suspected images
output_directory = os.path.join(directory, 'possibleanimals')
os.makedirs(output_directory, exist_ok=True)
# Iterate over all files in the directory
for filename in os.listdir(directory):
if filename.endswith('.jpg') or filename.endswith('.png'):
# Read the image
image = cv2.imread(os.path.join(directory, filename))
# Perform object detection on the image
results = model(image)
# Check if animal detections exist
if results.obj_detected: # Update this line to work with yolov5 library
animal_class_indexes = range(14, 24)
animal_detections = list(filter(lambda x: x.class_id in animal_class_indexes, results.objects()))
# Check if any animal detections were found
if len(animal_detections) > 0:
print('Animal detected in:', filename)
# Move the suspected image to the "possibleanimals" folder
shutil.move(os.path.join(directory, filename), os.path.join(output_directory, filename))
# Close all windows
cv2.destroyAllWindows()
# Path to the directory containing the images
directory = 'C:/Users/Bob/Pexels/Animals/candid/'
# Call the function to detect and move animals in the images
detect_and_move_animals(directory)
Make sure to use the correct pre-trained model and filename for the YOLOv5 version ('yolov5s.pt', 'yolov5m.pt', etc.).
Gradient
import os
import cv2
import statistics
import pandas as pd
import numpy as np
import tempfile
from skimage.metrics import structural_similarity as ssim
from scipy.ndimage.filters import gaussian_filter
from haarPsi import haar_psi_numpy
To use gradient descent to tweak contrast_amount until a certain mean level of haar_psi_numpy is reached, you can modify the original script by adding a gradient descent loop before applying the contrast modification to the image.
Here's the modified script with a gradient descent loop:
import os
import cv2
import statistics
import pandas as pd
import numpy as np
import tempfile
from skimage.metrics import structural_similarity as ssim
from scipy.ndimage.filters import gaussian_filter
from haarPsi import haar_psi_numpy
def imcontrastc(I, amount):
LUT = np.interp(np.arange(256), np.array([0, 64, 192, 256]), np.array([0, (0.25 - amount/4)*255, (0.75 + amount/4)*255, 255])).astype('uint8')
J = cv2.LUT(I, LUT)
return J
# Define a target haar_psi_numpy value
target_haar_psi = 0.8
learning_rate = 0.001
num_iterations = 100
def main(input_folder, save_images=False):
results = []
for file in os.listdir(input_folder):
filepath = os.path.join(input_folder, file)
# Read the image
img = cv2.imread(filepath, cv2.IMREAD_COLOR)
# Check if the image is valid (not None)
if img is not None:
# Initialize contrast_amount
contrast_amount = 0.44
# Gradient Descent Loop
for _ in range(num_iterations):
# Apply contrast modification
contrast_img = imcontrastc(img, contrast_amount)
# Calculate haar_psi_numpy() for the current contrast
haar_psi_c, _, _ = haar_psi_numpy(img, contrast_img)
# Calculate the error and derivative
error = haar_psi_c - target_haar_psi
d_contrast = error / num_iterations
# Update contrast_amount
contrast_amount -= learning_rate * d_contrast
# Clip contrast_amount between 0.4 and 0.8
contrast_amount = np.clip(contrast_amount, 0.4, 0.8)
# Modify the image using the updated contrast_amount value
contrast_img = imcontrastc(img, contrast_amount)
if save_images:
# Save distorted images
cv2.imwrite(os.path.join(output_dir, file[:-4] + '_contrast.jpg'), contrast_img)
# Append results to the list
results.append([file, 'contrast', contrast_amount, round(haar_psi_c, 3)])
# Create a pandas DataFrame from the results list
df = pd.DataFrame(results, columns=['Image Name', 'Distortion Type', 'Parameter', 'haar_psi_numpy'])
return df
input_folder = 'C:/Users/Bob/Downloads/100sampled/'
output_dir = 'C:/Users/Bob/Downloads/100sampled/Sub/distorted_images'
save_images = False
# Create output directory if it doesn't exist
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# Run the main function and get the DataFrame
results_df = main(input_folder, save_images)
print(results_df)
# Group the data by "Distortion Type" column
grouped_df = results_df.groupby("Distortion Type")
# Calculate the mean, standard deviation, and quantiles for each group
agg_df = grouped_df.agg(["mean", "std", lambda x: x.quantile(0.025), lambda x: x.quantile(0.975)])["haar_psi_numpy"]
# Rename the columns
agg_df.columns = ["Mean haar_psi", "SD", "Lower 2.5% Quantile", "Upper 2.5% Quantile"]
# Print the result
print(agg_df.round(3))
This script uses gradient descent to adjust the contrast_amount variable to achieve a certain target mean haar_psi_numpy value over a given number of iterations. Note that the number of iterations, the learning rate, and the target value can be adjusted as needed.
import os
import cv2
import statistics
import pandas as pd
import numpy as np
import tempfile
from skimage.metrics import structural_similarity as ssim
from scipy.ndimage.filters import gaussian_filter
for file in os.listdir(input_folder):
filepath = os.path.join(input_folder, file)
# Read the image
img = cv2.imread(filepath, cv2.IMREAD_COLOR)
# Check if the image is valid (not None)
if img is not None:
# Initialize contrast_amount
contrast_amount = 0.44
# Gradient Descent Loop
for i in range(num_iterations):
# Apply contrast modification
contrast_img = imcontrastc(img, contrast_amount)
# Calculate haar_psi_numpy() for the current contrast
haar_psi_c, _, _ = haar_psi_numpy(img, contrast_img)
# Calculate the error and derivative
error = haar_psi_c - target_haar_psi
d_contrast = error / contrast_amount # Updated calculation
# Update contrast_amount
contrast_amount -= learning_rate * d_contrast
# Clip contrast_amount between 0.4 and 0.8
contrast_amount = np.clip(contrast_amount, 0.4, 0.8)
# Print the status after each iteration
print(f'Image: {file} Iteration: {i+1}/{num_iterations} Contrast Amount: {contrast_amount:.4f} haar_psi_numpy: {haar_psi_c:.4f}')
# Modify the image using the updated contrast_amount value
contrast_img = imcontrastc(img, contrast_amount)
if save_images:
# Save distorted images
cv2.imwrite(os.path.join(output_dir, file[:-4] + '_contrast.jpg'), contrast_img)
# Append results to the list
results.append([file, 'contrast', contrast_amount, round(haar_psi_c, 3)])
# Create a pandas DataFrame from the results list
df = pd.DataFrame(results, columns=['Image Name', 'Distortion Type', 'Parameter', 'haar_psi_numpy'])
return df
I see the issue you're facing. The gradient descent code was not converging as expected. In fact, the derivative calculation with respect to contrast_amount was not accurate, which is why the optimization process did not work correctly.
You can try a different approach to achieve the desired haar_psi_numpy value by using a simple iterative search method without gradient descent. This method will search for possible optimal contrast_amount values by checking the haar_psi_numpy value when incrementing/decrementing the contrast_amount in each iteration.
Here's an update to the code with the iterative search approach:
import os
import cv2
import statistics
import pandas as pd
import numpy as np
import tempfile
from skimage.metrics import structural_similarity as ssim
from scipy.ndimage.filters import gaussian_filter
from haarPsi import haar_psi_numpy
def imcontrastc(I, amount):
LUT = np.interp(np.arange(256), np.array([0, 64, 192, 256]), np.array([0, (0.25 - amount/4)*255, (0.75 + amount/4)*255, 255])).astype('uint8')
J = cv2.LUT(I, LUT)
return J
# Define a target haar_psi_numpy value
target_haar_psi = 0.85
search_step = 0.001
num_iterations = 100
def main(input_folder, save_images=False):
results = []
for file in os.listdir(input_folder):
filepath = os.path.join(input_folder, file)
# Read the image
img = cv2.imread(filepath, cv2.IMREAD_COLOR)
# Check if the image is valid (not None)
if img is not None:
# Initialize contrast_amount
contrast_amount = 0.44
# Iterative Search Loop
for i in range(num_iterations):
# Apply contrast modification
contrast_img = imcontrastc(img, contrast_amount)
# Calculate haar_psi_numpy() for the current contrast
haar_psi_c, _, _ = haar_psi_numpy(img, contrast_img)
# Adjust contrast_amount based on haar_psi_c relative to target_haar_psi
if haar_psi_c < target_haar_psi:
contrast_amount += search_step
else:
contrast_amount -= search_step
# Clip contrast_amount between 0.4 and 0.8
contrast_amount = np.clip(contrast_amount, 0.4, 0.8)
# Print the status after each iteration
print(f'Image: {file} Iteration: {i+1}/{num_iterations} Contrast Amount: {contrast_amount:.4f} haar_psi_numpy: {haar_psi_c:.4f}')
# Modify the image using the updated contrast_amount value
contrast_img = imcontrastc(img, contrast_amount)
if save_images:
# Save distorted images
cv2.imwrite(os.path.join(output_dir, file[:-4] + '_contrast.jpg'), contrast_img)
# Append results to the list
results.append([file, 'contrast', contrast_amount, round(haar_psi_c, 3)])
# Create a pandas DataFrame from the results list
df = pd.DataFrame(results, columns=['Image Name', 'Distortion Type', 'Parameter', 'haar_psi_numpy'])
return df
input_folder = 'C:/Users/Bob/Downloads/100sampled/'
output_dir = 'C:/Users/Bob/Downloads/100sampled/Sub/distorted_images'
save_images = False
# Create output directory if it doesn't exist
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# Run the main function and get the DataFrame
results_df = main(input_folder, save_images)
print(results_df)
This code observes how the haar_psi_numpy value changes when the contrast_amount increases or decreases. It may not be as fast as gradient descent optimization, but in this case, it can help search iteratively for an optimal value that gets closer to the target_haar_psi without complex calculations. Feel free to adjust the search_step and num_iterations parameters as needed to get better results.