initial commit
This commit is contained in:
81
jpeg_corrupt_test.py
Normal file
81
jpeg_corrupt_test.py
Normal file
@@ -0,0 +1,81 @@
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
def corrupt_data(data, corruption_type='modify', severity=1):
|
||||
"""
|
||||
对二进制数据进行损坏
|
||||
:param data: 原始二进制数据
|
||||
:param corruption_type: 损坏类型 ('modify', 'shift', 'loss')
|
||||
:param severity: 损坏严重程度 (1-10)
|
||||
:return: 损坏后的二进制数据
|
||||
"""
|
||||
data = bytearray(data) # 转换为可变的 bytearray
|
||||
length = len(data)
|
||||
|
||||
if corruption_type == 'modify':
|
||||
# 修改部分数据
|
||||
for i in range(severity * 5):
|
||||
idx = np.random.randint(0, length)
|
||||
data[idx] = np.random.randint(0, 256)
|
||||
|
||||
elif corruption_type == 'shift':
|
||||
# 数据移位
|
||||
shift = severity * 10
|
||||
data = data[shift:] + data[:shift]
|
||||
|
||||
elif corruption_type == 'loss':
|
||||
# 数据丢失
|
||||
loss_start = np.random.randint(0, length - severity * 10)
|
||||
data[loss_start:loss_start + severity * 10] = b'\x00' * (severity * 10)
|
||||
|
||||
return bytes(data)
|
||||
|
||||
def main():
|
||||
# 打开摄像头
|
||||
cap = cv2.VideoCapture(0)
|
||||
|
||||
if not cap.isOpened():
|
||||
print("无法打开摄像头")
|
||||
return
|
||||
|
||||
while True:
|
||||
# 读取一帧图像
|
||||
ret, frame = cap.read()
|
||||
if not ret:
|
||||
print("无法读取图像")
|
||||
break
|
||||
|
||||
frame = cv2.resize(frame, (224, 224))
|
||||
|
||||
# 显示原始图像
|
||||
cv2.imshow('Original Image', frame)
|
||||
|
||||
# 将图像编码为 JPEG 格式的二进制数据
|
||||
ret, jpeg_data = cv2.imencode('.jpg', frame)
|
||||
if not ret:
|
||||
print("图像编码失败")
|
||||
break
|
||||
|
||||
# 对二进制数据进行损坏
|
||||
corrupted_data = corrupt_data(jpeg_data, corruption_type='modify', severity=2)
|
||||
|
||||
# 解码损坏后的二进制数据
|
||||
corrupted_image = cv2.imdecode(np.frombuffer(corrupted_data, dtype=np.uint8), cv2.IMREAD_COLOR)
|
||||
|
||||
if corrupted_image is None:
|
||||
print("损坏后的数据无法解码")
|
||||
else:
|
||||
# 显示损坏后的图像
|
||||
cv2.imshow('Corrupted Image', corrupted_image)
|
||||
|
||||
# 等待用户按键
|
||||
key = cv2.waitKey(0)
|
||||
if key == ord('q'): # 按下 'q' 键退出
|
||||
break
|
||||
|
||||
# 释放摄像头并关闭所有窗口
|
||||
cap.release()
|
||||
cv2.destroyAllWindows()
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user