图片检查 python脚本

目录

获取宽高,检查图像是否破坏

图片检查 python脚本

直接度头部信息

获取图像diff,可视化出来


获取宽高,检查图像是否破坏

import random
import time

import cv2
from PIL import Image
import os

def get_image_resolution(image_path):
    width =0
    height =0
    try:
        img = cv2.VideoCapture(image_path)
        width = img.get(cv2.CAP_PROP_FRAME_WIDTH)
        height = img.get(cv2.CAP_PROP_FRAME_HEIGHT)
    except Exception as e:
        print('e' ,e)
    return int(width), int(height)

def check_img(image_path):
    try:
        img = Image.open(image_path)
        img.verify()  # Verify that it is, in fact an image
        return True
    except (IOError, SyntaxError) as e:
        return False

def generate_random_4k_image(output_path):
    # 4K 分辨率的宽度和高度
    width, height = 3840, 2160

    # 创建一个新的图像,RGB模式
    image = Image.new('RGB', (width, height))

    # 获取像素数据的访问权限
    pixels = image.load()

    # 为每个像素分配随机颜色
    for x in range(width):
        for y in range(height):
            # 随机生成RGB值
            r = random.randint(0, 255)
            g = random.randint(0, 255)
            b = random.randint(0, 255)
            pixels[x, y] = (r, g, b)

    # 保存图像
    image.save(output_path)

def check_file_size(file_path,size_level=0.5*1000):
    file_size=os.path.getsize(file_path)
    if file_size<size_level:
        return False,file_size
    return True,file_size
if __name__ == '__main__':
    image_path='aaa.jpg'
    image_path='bbb.jpg'
    image_path='aaa.py'

    # generate_random_4k_image(image_path)


    # 1479904
    start=time.time()
    res,file_size=check_file_size(image_path,10*1000)
    print('size time',res,time.time()-start)
    print(res)

    start=time.time()
    res=get_image_resolution(image_path)
    print('time',time.time()-start)
    print(res)

    start=time.time()
    res=check_img(image_path)
    print('time2',time.time()-start)
    print(res)

但是读图0kb的图像用了190ms

4k图像用了200多ms,还是Pil相对比较快。

图片检查 python脚本

import os
from PIL import Image

def is_image_broken(image_path):
    try:
        img = Image.open(image_path)
        img.verify()  # Verify that it is, in fact an image
        return False
    except (IOError, SyntaxError) as e:
        return True

def check_images_in_directory(directory):
    broken_images = []
    for root, _, files in os.walk(directory):
        for file in files:
            if file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.tiff', '.webp')):
                image_path = os.path.join(root, file)
                if is_image_broken(image_path):
                    broken_images.append(image_path)
    return broken_images

directory_to_check = '/path/to/your/directory'
broken_images = check_images_in_directory(directory_to_check)

if broken_images:
    print("The following images are broken:")
    for img in broken_images:
        print(img)
else:
    print("No broken images found.")

直接度头部信息

def get_image_resolution(file_path):
    with open(file_path, 'rb') as f:
        # 检查文件类型以确定如何处理
        file_type = f.read(8)

        # 判断是JPEG文件
        if file_type[:2] == b'\xff\xd8':
            # Skip header and move to resolution data
            f.seek(163)
            height = f.read(2)
            width = f.read(2)
            # Convert the bytes to integers
            width = int.from_bytes(width, 'big')
            height = int.from_bytes(height, 'big')
            return (width, height)

        # 判断是PNG文件
        elif file_type[:8] == b'\x89PNG\r\n\x1a\n':
            # PNG resolution is stored in the IHDR chunk, at byte 16-24
            f.seek(16)
            width = f.read(4)
            height = f.read(4)
            # Convert the bytes to integers
            width = int.from_bytes(width, 'big')
            height = int.from_bytes(height, 'big')
            return (width, height)

        else:
            raise ValueError("Unsupported image format")

# Example usage:
jpeg_resolution = get_image_resolution('example.jpg')
print("JPEG Resolution:", jpeg_resolution)

png_resolution = get_image_resolution('example.png')
print("PNG Resolution:", png_resolution)

获取图像diff,可视化出来

import glob
import os

from moviepy.editor import VideoFileClip
import numpy as np


def check_file_size(file_path, size_level=0.5 * 1000):
    file_size = os.path.getsize(file_path)
    if file_size < size_level:
        return False, file_size
    return True, file_size


def process_frame(frame):
    # 获取帧的宽度和高度
    height, width, _ = frame.shape

    width_part=960
    h_part=576
    # 前两列: 左半部分 (前 width // 2 列)
    part1_2 = frame[h_part:h_part*2, :width_part, :]
    part1_3 = frame[h_part*2:h_part*3, :width_part, :]

    part2_2 = frame[h_part:h_part*2, width_part:width_part*2, :]
    part2_3 = frame[h_part*2:h_part*3, width_part:width_part*2, :]

    part3_2 = frame[h_part:h_part*2, width_part*2:width_part*3, :]
    part3_3 = frame[h_part*2:h_part*3,width_part*2:width_part*3, :]

    pic_right=np.zeros((2880,960,3),dtype=np.uint8)

    pic_right[h_part:h_part*2]= np.clip(np.abs(part1_2.astype(np.int16) - part1_3.astype(np.int16)), 0, 255).astype(np.uint8)
    pic_right[h_part*2:h_part*3]= np.clip(np.abs(part2_2.astype(np.int16) - part2_3.astype(np.int16)), 0, 255).astype(np.uint8)
    pic_right[h_part*3:4*h_part]= np.clip(np.abs(part3_2.astype(np.int16) - part3_3.astype(np.int16)), 0, 255).astype(np.uint8)

    # 将原帧与差值列拼接
    new_frame = np.concatenate((frame, pic_right), axis=1)

    return new_frame


dir_ar=r'C:\Users\Administrator\Downloads\liauto_fv_960_arrow_36_6f_150_depth_nomask,mask_e20_e30\aa'

fils=glob.glob(os.path.join(dir_ar,'*.mp4'))

out_dir=r'C:\Users\Administrator\Downloads\liauto_fv_960_arrow_36_6f_150_depth_nomask,mask_e20_e30/diff/'
os.makedirs(out_dir,exist_ok=True)
for file in fils:
    size_ok,_= check_file_size(file)
    if size_ok:
        video = VideoFileClip(file)
    
        # 对每一帧应用帧处理函数
        new_video = video.fl_image(process_frame)
    
        # 保存处理后的视频
        new_video.write_videofile(out_dir+os.path.basename(file))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI算法网奇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值