Skip to content

Commit f81a687

Browse files
authored
移除down_urls,新增read_web_img
1 parent 611e320 commit f81a687

File tree

2 files changed

+48
-22
lines changed

2 files changed

+48
-22
lines changed

bobotools/img_tools.py

Lines changed: 47 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,65 @@
1-
import os
21
import hashlib
32
from tqdm import tqdm
43
import numpy as np
5-
import uuid
64
import cv2
7-
import socket
8-
from urllib.request import urlretrieve
95
import torch
10-
6+
import base64
7+
import urllib.request
118

129
class Img_Tools(object):
1310
"""
14-
Img操作
11+
Img工具类
1512
"""
1613

1714
def __init__(self):
1815
pass
19-
16+
2017
@staticmethod
21-
def down_urls(url_list, save_path, time=5):
22-
"""
23-
根据url下载图片,随机uuid命名。
18+
def read_web_img(image_url=None,image_file=None,image_base64=None,url_time_out=10):
19+
'''
20+
参数三选一,当传入多个参数,仅返回最高优先级的图像
21+
22+
优先级: 文件 > base64 > url
23+
24+
url_time_out : URL下载耗时限制,默认10秒
25+
'''
26+
if image_file:
27+
try:
28+
img = cv2.imdecode(np.frombuffer(image_file, np.uint8), cv2.IMREAD_COLOR)
29+
if img.any():
30+
return img
31+
else:
32+
return 'IMAGE_ERROR_UNSUPPORTED_FORMAT'
33+
except:
34+
return 'IMAGE_ERROR_UNSUPPORTED_FORMAT'
2435

25-
url_list(list): URL列表 eg:['http://a.jpg', http://aaacc', ...]
26-
save_path(str): 图像保存路径
27-
time(int):耗时限制,单位s
28-
"""
29-
socket.setdefaulttimeout(time) # 超时限制
30-
assert len(url_list) > 0 and os.path.isdir(save_path) # 验证文件夹是否存在
31-
print("start download imgs...")
32-
for url in tqdm(url_list):
36+
elif image_base64:
3337
try:
34-
urlretrieve(url, save_path + str(uuid.uuid1()) + ".jpg")
35-
except socket.timeout:
36-
print("error url: ", url, "\n")
38+
img = base64.b64decode(image_base64)
39+
img_array = np.frombuffer(img, np.uint8)
40+
img = cv2.imdecode(img_array, cv2.IMREAD_COLOR)
41+
if img.any():
42+
return img
43+
else:
44+
return 'IMAGE_ERROR_UNSUPPORTED_FORMAT'
45+
except:
46+
return 'IMAGE_ERROR_UNSUPPORTED_FORMAT'
47+
elif image_url:
48+
try:
49+
resp = urllib.request.urlopen(image_url,time_out=url_time_out)
50+
except:
51+
return 'URL_DOWNLOAD_TIMEOUT'
52+
try:
53+
image = np.asarray(bytearray(resp.read()), dtype="uint8")
54+
img = cv2.imdecode(image, cv2.IMREAD_COLOR)
55+
if img.any():
56+
return img
57+
else:
58+
return 'IMAGE_ERROR_UNSUPPORTED_FORMAT'
59+
except:
60+
return 'INVALID_IMAGE_URL'
61+
else:
62+
return 'MISSING_ARGUMENTS'
3763

3864
@staticmethod
3965
def plot_bbox(img, bbox, name, prob):

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
description="bobotools",
1010
long_description=open("README.md", "r").read(),
1111
long_description_content_type="text/markdown",
12-
version="0.4.3", # 版本
12+
version="0.4.4", # 版本
1313
install_requires=["tqdm", "opencv-python", "numpy", "torch"],
1414
python_requires=">=3.6",
1515
include_package_data=True,

0 commit comments

Comments
 (0)