Advertisement
Guest User

getimg.py

a guest
Oct 21st, 2016
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.87 KB | None | 0 0
  1. import numpy as np
  2. import cv2
  3.  
  4. REMAINING = 'remaining'
  5. PROCESSED = 'processed'
  6.  
  7. def get_chars(stream, needle, buffer=None, chunksize=1024, mode=REMAINING):
  8.     """
  9.    Read chunks from stream and stop when needle was found.
  10.    
  11.    Return needle and all characters after it if mode is 'remaining'.
  12.    Return all characters before needle and needle if mode is 'processed'.
  13.    
  14.    Note that no more chunks are read when needle was found. Therefore,
  15.    characters might remain untouched at the stream. These characters are
  16.    not included in the result.
  17.    """
  18.     if not needle:
  19.         raise ValueError('needle must not be empty')
  20.     if mode not in (REMAINING, PROCESSED):
  21.         raise ValueError('unknown mode')
  22.     empty = type(needle)()
  23.     if not buffer:
  24.         buffer = empty
  25.     processed = []
  26.     bufsize = len(needle) - 1
  27.     chunks = iter(lambda: stream.read(chunksize), empty)
  28.     for chunk in chunks:
  29.         haystack = buffer + chunk
  30.         index = haystack.find(needle)
  31.         if index >= 0:
  32.             if mode == PROCESSED:
  33.                 tail = haystack[:index + len(needle)]
  34.                 return empty.join(processed) + tail
  35.             return haystack[index:]
  36.         buffer = haystack[-bufsize:]
  37.         if mode == PROCESSED:
  38.             chars = haystack[:-bufsize]
  39.             processed.append(chars)
  40.     return empty
  41.  
  42. def get_image_data(stream, start_mark=b'\xff\xd8', stop_mark=b'\xff\xd9'):
  43.     data = get_chars(stream, start_mark, mode=REMAINING)
  44.     if not data:
  45.         raise IOError('missing start mark')
  46.     buf = data[len(start_mark):]
  47.     data = get_chars(stream, stop_mark, buffer=buf, mode=PROCESSED)
  48.     if not data:
  49.         raise IOError('missing stop mark')
  50.     return data
  51.  
  52. def get_image(stream):
  53.     data = get_image_data(stream)
  54.     buf = np.fromstring(data, dtype=np.uint8)
  55.     return cv2.imdecode(buf, 1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement