python类imdecode()的实例源码

tolmdb.py 文件源码 项目:crnn 作者: wulivicte 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def checkImageIsValid(imageBin):
    if imageBin is None:
        return False
    try:
        imageBuf = np.fromstring(imageBin, dtype=np.uint8)
        img = cv2.imdecode(imageBuf, cv2.IMREAD_GRAYSCALE)
        imgH, imgW = img.shape[0], img.shape[1]
    except:
        return False
    else:
        if imgH * imgW == 0:
            return False        
    return True
encodings.py 文件源码 项目:moVi 作者: netsecIITK 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def decode(self, byte_list):
        return cv2.imdecode(byte_list, cv2.IMREAD_COLOR)
log_utils.py 文件源码 项目:pybot 作者: spillai 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def decode(self, data): 
        msg = image_t.decode(data)
        if msg.pixelformat == image_t.PIXEL_FORMAT_GRAY: 
            return im_resize(np.asarray(bytearray(msg.data), dtype=np.uint8).reshape(msg.height, msg.width), scale=self.scale)
        elif msg.pixelformat == image_t.PIXEL_FORMAT_MJPEG: 
            im = cv2.imdecode(np.asarray(bytearray(msg.data), dtype=np.uint8), -1)
            return im_resize(im, scale=self.scale)
        else: 
            raise RuntimeError('Unknown pixelformat for ImageDecoder')
log_utils.py 文件源码 项目:pybot 作者: spillai 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
def decode_rgb(self, data): 
        w, h = data.image.width, data.image.height;
        if data.image.image_data_format == self.image_msg_t_.VIDEO_RGB_JPEG: 
            img = cv2.imdecode(np.asarray(bytearray(data.image.image_data), dtype=np.uint8), -1)
            bgr = img.reshape((h,w,3))[::self.skip, ::self.skip, :]             
        else: 
            img = np.fromstring(data.image.image_data, dtype=np.uint8)
            rgb = img.reshape((h,w,3))[::self.skip, ::self.skip, :] 
            bgr = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)
        if not self.bgr: 
            return cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
        else: 
            return bgr
bag_utils.py 文件源码 项目:pybot 作者: spillai 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def compressed_imgmsg_to_cv2(cmprs_img_msg, desired_encoding = "passthrough"):
    """
    Convert a sensor_msgs::CompressedImage message to an OpenCV :cpp:type:`cv::Mat`.

    :param cmprs_img_msg:   A :cpp:type:`sensor_msgs::CompressedImage` message
    :param desired_encoding:  The encoding of the image data, one of the following strings:

       * ``"passthrough"``
       * one of the standard strings in sensor_msgs/image_encodings.h

    :rtype: :cpp:type:`cv::Mat`
    :raises CvBridgeError: when conversion is not possible.

    If desired_encoding is ``"passthrough"``, then the returned image has the same format as img_msg.
    Otherwise desired_encoding must be one of the standard image encodings

    This function returns an OpenCV :cpp:type:`cv::Mat` message on success, or raises :exc:`cv_bridge.CvBridgeError` on failure.

    If the image only has one channel, the shape has size 2 (width and height)
    """
    str_msg = cmprs_img_msg.data
    buf = np.ndarray(shape=(1, len(str_msg)),
                      dtype=np.uint8, buffer=cmprs_img_msg.data)
    im = cv2.imdecode(buf, cv2.IMREAD_ANYCOLOR)

    if desired_encoding == "passthrough":
        return im

    try:
        res = cvtColor2(im, "bgr8", desired_encoding)
    except RuntimeError as e:
        raise CvBridgeError(e)

    return res
tcp_utils.py 文件源码 项目:pybot 作者: spillai 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def read_image(conn): 
    try: 
        length = int(recvall(conn, 16))
    except:
        import sys
        print "Unexpected error:", sys.exc_info()[0]
        return False, None

    stringData = recvall(conn, length)
    data = np.fromstring(stringData, dtype='uint8')
    decimg = cv2.imdecode(data, 1)
    print 'Image received ', decimg.shape
    return True, decimg
predict.py 文件源码 项目:pokedex-as-it-should-be 作者: leotok 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def predict_knn(image_file):
    image = cv2.imdecode(np.fromstring(image_file.read(), np.uint8), cv2.CV_LOAD_IMAGE_UNCHANGED)
    if image is not None:
        features = np.array([extract_color_histogram(image)])
        loaded_model = pickle.load(open(MODEL_PATH + "/knn_model.sav", 'rb'))

        return loaded_model.predict(features)[0]
    else:
        raise "Failed"
predict.py 文件源码 项目:pokedex-as-it-should-be 作者: leotok 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def predict_mlp(image_file):
    image = cv2.imdecode(np.fromstring(image_file.read(), np.uint8), cv2.CV_LOAD_IMAGE_UNCHANGED)
    if image is not None:
        features = np.array([image_to_feature_vector(image)])
        loaded_model = pickle.load(open(MODEL_PATH + "/mlp_model.sav", 'rb'))
        scaler = pickle.load(open(MODEL_PATH + "/scaler_model.sav", "rb"))
        features = scaler.transform(features)

        return loaded_model.predict(features)[0]
    else:
        raise "Failed"
faceswapper.py 文件源码 项目:FaceSwapper 作者: QuantumLiu 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def read_im(self,fname,scale=1):
        '''
        ????
        '''
# =============================================================================
#         im = cv2.imread(fname, cv2.IMREAD_COLOR)
# =============================================================================
        im = cv2.imdecode(np.fromfile(fname,dtype=np.uint8),-1)
        if type(im)==type(None):
            print(fname)
            raise ValueError('Opencv read image {} error, got None'.format(fname))
        return im
calibrator.py 文件源码 项目:camera_calibration_frontend 作者: groundmelon 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def image_from_archive(archive, name):
    """
    Load image PGM file from tar archive. 

    Used for tarfile loading and unit test.
    """
    member = archive.getmember(name)
    imagefiledata = numpy.fromstring(archive.extractfile(member).read(-1), numpy.uint8)
    imagefiledata.resize((1, imagefiledata.size))
    return cv2.imdecode(imagefiledata, cv2.IMREAD_COLOR)
soja_someTest.py 文件源码 项目:soja_box 作者: iTaa 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def cv_test(original_image_name):
    with open(original_image_name) as f:
        img = cv2.imdecode(f, 1)
        img2 = cv2.imread(original_image_name)
        if img == img2:
            print("yes you are right")
        else:
            print("can not do this")
utils.py 文件源码 项目:MIL.pytorch 作者: gujiuxiang 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def url_to_image(url):
    # download the image, convert it to a NumPy array, and then read
    # it into OpenCV format
    resp = urllib.urlopen(url)
    image = np.asarray(bytearray(resp.read()), dtype="uint8")
    image = cv2.imdecode(image, cv2.IMREAD_COLOR)

    # return the image
    return image
poc.py 文件源码 项目:Emotion-Recognition 作者: Shujathlive 项目源码 文件源码 阅读 50 收藏 0 点赞 0 评论 0
def format_image(image):
  if len(image.shape) > 2 and image.shape[2] == 3:
    image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  else:
    image = cv2.imdecode(image, cv2.CV_LOAD_IMAGE_GRAYSCALE)
  faces = cascade_classifier.detectMultiScale(
      image,
      scaleFactor = 1.3,
      minNeighbors = 5
  )
  # None is we don't found an image
  if not len(faces) > 0:
    return None
  max_area_face = faces[0]
  for face in faces:
    if face[2] * face[3] > max_area_face[2] * max_area_face[3]:
      max_area_face = face
  # Chop image to face
  face = max_area_face
  image = image[face[1]:(face[1] + face[2]), face[0]:(face[0] + face[3])]
  # Resize image to network size
  try:
    image = cv2.resize(image, (SIZE_FACE, SIZE_FACE), interpolation = cv2.INTER_CUBIC) / 255.
  except Exception:
    print("[+] Problem during resize")
    return None
  # cv2.imshow("Lol", image)
  # cv2.waitKey(0)
  return image

# Load Model
recv.py 文件源码 项目:python-streaming-server 作者: golubaca 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def rcv():
    data = b''
    while 1:

        try:
            r = client_socket.recv(90456)
            if len(r) == 0:
                exit(0)
            a = r.find(b'END!')
            if a != -1:
                data += r[:a]
                break
            data += r
        except Exception as e:
            print(e)
            continue
    nparr = numpy.fromstring(data, numpy.uint8)
    frame = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
    if type(frame) is type(None):
        pass
    else:
        try:
            cv2.imshow(name,frame)
            if cv2.waitKey(10) == ord('q'):
                client_socket.close()
                sys.exit()
        except:
            client_socket.close()
            exit(0)
imutils.py 文件源码 项目:ATX 作者: NetEaseGame 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def _open_data_url(data, flag=cv2.IMREAD_COLOR):
    pos = data.find('base64,')
    if pos == -1:
        raise IOError("data url is invalid, head %s" % data[:20])

    pos += len('base64,')
    raw_data = base64.decodestring(data[pos:])
    image = np.asarray(bytearray(raw_data), dtype="uint8")
    image = cv2.imdecode(image, flag)
    return image
imutils.py 文件源码 项目:ATX 作者: NetEaseGame 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def url_to_image(url, flag=cv2.IMREAD_COLOR):
    """ download the image, convert it to a NumPy array, and then read
    it into OpenCV format """
    resp = urlopen(url)
    image = np.asarray(bytearray(resp.read()), dtype="uint8")
    image = cv2.imdecode(image, flag)
    return image
mixins.py 文件源码 项目:ATX 作者: NetEaseGame 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def str2img(jpgstr, orientation=None):
    import numpy as np
    import cv2
    arr = np.fromstring(jpgstr, np.uint8)
    img = cv2.imdecode(arr, cv2.IMREAD_COLOR)
    if orientation == 1:
        return cv2.flip(cv2.transpose(img), 0) # counter-clockwise
    if orientation == 3:
        return cv2.flip(cv2.transpose(img), 1) # clockwise
    return img
alg.py 文件源码 项目:image-segmentation 作者: alexlouden 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def download_image(url):
    response = requests.get(url, stream=True, timeout=5)
    # TODO use grequests
    # Raise exception on error
    response.raise_for_status()
    numpy_array = np.asarray(bytearray(response.raw.read()), dtype=np.uint8)
    image = cv2.imdecode(numpy_array, cv2.IMREAD_COLOR)
    # TODO: handle transparency (load using cv2.IMREAD_UNCHANGED and convert alpha layer to white?)
    return image
actions.py 文件源码 项目:Yugioh-bot 作者: will7200 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def get_img_from_screen_shot(self):
        screen_shot = self.take_png_screenshot()
        nparr = np.fromstring(screen_shot, np.uint8)
        img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
        return img
app.py 文件源码 项目:StreamMotionDetection 作者: henry54809 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def get_mjpeg_stream_image(stream):
    global bytes
    while True:
        bytes += stream.read(20000)
        a = bytes.find(b'\xff\xd8')
        b = bytes.find(b'\xff\xd9')
        if a!= -1 and b != -1:
             jpg = bytes[a:b+2]
             bytes = bytes[b+2:]
             img = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.IMREAD_COLOR)
             q.put_nowait(img)
        cv2.waitKey(1)


问题


面经


文章

微信
公众号

扫码关注公众号