Python cv2 模块,IMWRITE_JPEG_QUALITY 实例源码

我们从Python开源项目中,提取了以下17个代码示例,用于说明如何使用cv2.IMWRITE_JPEG_QUALITY

项目:blind-watermark    作者:linyacool    | 项目源码 | 文件源码
def encode(img_path, wm_path, res_path, alpha):
    img = cv2.imread(img_path)
    img_f = np.fft.fft2(img)
    height, width, channel = np.shape(img)
    watermark = cv2.imread(wm_path)
    wm_height, wm_width = watermark.shape[0], watermark.shape[1]
    x, y = range(height / 2), range(width)
    random.seed(height + width)
    random.shuffle(x)
    random.shuffle(y)
    tmp = np.zeros(img.shape)
    for i in range(height / 2):
        for j in range(width):
            if x[i] < wm_height and y[j] < wm_width:
                tmp[i][j] = watermark[x[i]][y[j]]
                tmp[height - 1 - i][width - 1 - j] = tmp[i][j]
    res_f = img_f + alpha * tmp
    res = np.fft.ifft2(res_f)
    res = np.real(res)
    cv2.imwrite(res_path, res, [int(cv2.IMWRITE_JPEG_QUALITY), 100])
项目:blind-watermark    作者:linyacool    | 项目源码 | 文件源码
def decode(ori_path, img_path, res_path, alpha):
    ori = cv2.imread(ori_path)
    img = cv2.imread(img_path)
    ori_f = np.fft.fft2(ori)
    img_f = np.fft.fft2(img)
    height, width = ori.shape[0], ori.shape[1]
    watermark = (ori_f - img_f) / alpha
    watermark = np.real(watermark)
    res = np.zeros(watermark.shape)
    random.seed(height + width)
    x = range(height / 2)
    y = range(width)
    random.shuffle(x)
    random.shuffle(y)
    for i in range(height / 2):
        for j in range(width):
            res[x[i]][y[j]] = watermark[i][j]
    cv2.imwrite(res_path, res, [int(cv2.IMWRITE_JPEG_QUALITY), 100])
项目:soja_box    作者:iTaa    | 项目源码 | 文件源码
def resize_image(img_path, mini_size=480, jpeg_quality=80):
    """
    ??image
    :param img_path: image???
    :param mini_size: ??????
    :param jpeg_quality: jpeg?????
    """
    org_img = cv2.imread(img_path)
    img_w = org_img.shape[0]
    img_h = org_img.shape[1]
    if max(img_w, img_h) > mini_size:
        if img_w > img_h:
            img_w = mini_size * img_w // img_h
            img_h = mini_size
        else:
            img_h = mini_size * img_h // img_w
            img_w = mini_size
    dist_size = (img_h, img_w)
    r_image = cv2.resize(org_img, dist_size, interpolation=cv2.INTER_AREA)
    params = [cv2.IMWRITE_JPEG_QUALITY, jpeg_quality]
    img_name = img_path + '_New.jpg'
    cv2.imwrite(img_name, r_image, params=[cv2.IMWRITE_JPEG_QUALITY, params])
项目:CV_backend    作者:ai-fake-news-team    | 项目源码 | 文件源码
def cv2_ELA(name):
    input_image = cv2.imread(name)

    scale = 15
    quality = 75

    cv2.imwrite(base+'ELA/temp.jpg', input_image, [cv2.IMWRITE_JPEG_QUALITY, quality])

    compressed_image = cv2.imread(base+'ELA/temp.jpg')

    output_image = (input_image - compressed_image) * scale

    gray_image = cv2.cvtColor(output_image, cv2.COLOR_BGR2GRAY)

    nonzero = cv2.countNonZero(gray_image)
    total = output_image.shape[0] * output_image.shape[1]
    zero = total - nonzero
    ratio = zero * 100 / float(total)

    cv2.imwrite(base+'ELA/results/{}_results.png'.format(name), output_image)
    return ratio, output_image
项目:opencv-helpers    作者:abarrak    | 项目源码 | 文件源码
def save(path, image, jpg_quality=None, png_compression=None):
  '''
  persist :image: object to disk. if path is given, load() first.
  jpg_quality: for jpeg only. 0 - 100 (higher means better). Default is 95.
  png_compression: For png only. 0 - 9 (higher means a smaller size and longer compression time).
                  Default is 3.
  '''
  if isinstance(image, str):
    image = load(str)

  if jpg_quality:
    cv.imwrite(path, image, [cv.IMWRITE_JPEG_QUALITY, jpg_quality])
  elif png_compression:
    cv.imwrite(path, image, [cv.IMWRITE_PNG_COMPRESSION, png_compression])
  else:
    cv.imwrite(path, image)
项目:moVi    作者:netsecIITK    | 项目源码 | 文件源码
def encode(self, frame):
        return cv2.imencode('.jpg',
                            frame,
                            [cv2.IMWRITE_JPEG_QUALITY, self.quality])[1]
项目:pybot    作者:spillai    | 项目源码 | 文件源码
def send_image(s, im, scale=1.0, encode_param=[int(cv2.IMWRITE_JPEG_QUALITY),90]):
    # Will not upsample image for bandwidth reasons
    if scale < 1: 
        im = cv2.resize(im, None, fx=scale, fy=scale)
    result, imgencode = cv2.imencode('.jpg', im, encode_param)
    data = np.array(imgencode)
    stringData = data.tostring()
    s.send( str(len(stringData)).ljust(16))
    s.send( stringData )
项目:image-segmentation    作者:alexlouden    | 项目源码 | 文件源码
def export_segmented_image(self, filename):

        cv2.imwrite(filename, self.segmented_image, (cv2.IMWRITE_JPEG_QUALITY, 80))
项目:mxnet_tk1    作者:starimpact    | 项目源码 | 文件源码
def pack_img(header, img, quality=80, img_fmt='.jpg'):
    """pack an image into MXImageRecord

    Parameters
    ----------
    header : IRHeader
        header of the image record
    img : numpy.ndarray
        image to pack
    quality : int
        quality for JPEG encoding. 1-100, or compression for PNG encoding. 1-9.
    img_fmt : str
        Encoding of the image. .jpg for JPEG, .png for PNG.

    Returns
    -------
    s : str
        The packed string
    """
    assert opencv_available
    jpg_formats = set(['.jpg', '.jpeg', '.JPG', '.JPEG'])
    png_formats = set(['.png', '.PNG'])
    encode_params = None
    if img_fmt in jpg_formats:
        encode_params = [cv2.IMWRITE_JPEG_QUALITY, quality]
    elif img_fmt in png_formats:
        encode_params = [cv2.IMWRITE_PNG_COMPRESSION, quality]

    ret, buf = cv2.imencode(img_fmt, img, encode_params)
    assert ret, 'failed encoding image'
    return pack(header, buf.tostring())
项目:SkinLesionNeuralNetwork    作者:Neurality    | 项目源码 | 文件源码
def save_array_jpg(array,n_images,folder='array_images',name='array_'):
    """
        Save a numpy array as images, using rows as single images.

        Keyword arguments:
        array -- numpy array containing the images with shape (n_images, [1,] width, height)
        n_images -- number of images that need to be saved
        folder -- the path where to save the model (without ending '/')(default '.')
        name -- The name of the saved image files (default 'array_')

        """
    #elimino il canale grigio(unico)
    if (len(array.shape) == 4) and (array.shape[1] == 1):
        print "L'array e' 4 dimensionale e ha solo un canale"
        array = np.reshape(array,(array.shape[0],array.shape[2],array.shape[3]))

        #Normalizzo arrray
        array -=array.min()
        array *= 255.0/(array.max())


        if np.amax(array)<=1:
            #print "IL MASSIMO DELL'array e' MENO di 1"
            #print np.amax(array)
            array = np.multiply(array,255.0)
            #else:
            #print "IL MASSIMO DELL'array e' piu di 1"    
            #print np.amax(array)

            for i in xrange(n_images):

                if i%100 == 0:
                    print('saved jpgs '+ str(i) +"/" + str(n_images))
                    print array[i]

                    cv2.imwrite('./'+folder+'/'+str(i)+'_'+name+'.jpg', array[i], [int(cv2.IMWRITE_JPEG_QUALITY), 80])
项目:main    作者:templerobotics    | 项目源码 | 文件源码
def sendImage(self, image, quality = 45):
        #Writes the image to a temporary file. This is where the image compression occurs
        cv2.imwrite('temp.jpg', image, (cv2.IMWRITE_JPEG_QUALITY, quality))
        #Sends the 'start' signal
        self._client.sendto('start', self._address)
        #Opens the file for sending
        with open('temp.jpg', 'rb') as handle:
            data = handle.read(self.bufferSize)
            while data:
                if self._client.sendto(data, self._address):
                    data = handle.read(self.bufferSize)
        self._client.sendto('end', self._address)
项目:ternarynet    作者:czhu95    | 项目源码 | 文件源码
def _augment(self, img, q):
        enc = cv2.imencode('.jpg', img, [cv2.IMWRITE_JPEG_QUALITY, q])[1]
        return cv2.imdecode(enc, 1)
项目:Vehicle_ReID    作者:starimpact    | 项目源码 | 文件源码
def pack_img(header, img, quality=95, img_fmt='.jpg'):
    """pack an image into MXImageRecord

    Parameters
    ----------
    header : IRHeader
        header of the image record
        header.label can be a number or an array.
    img : numpy.ndarray
        image to pack
    quality : int
        quality for JPEG encoding. 1-100, or compression for PNG encoding. 1-9.
    img_fmt : str
        Encoding of the image. .jpg for JPEG, .png for PNG.

    Returns
    -------
    s : str
        The packed string
    """
    assert opencv_available
    jpg_formats = ['.JPG', '.JPEG']
    png_formats = ['.PNG']
    encode_params = None
    if img_fmt.upper() in jpg_formats:
        encode_params = [cv2.IMWRITE_JPEG_QUALITY, quality]
    elif img_fmt.upper() in png_formats:
        encode_params = [cv2.IMWRITE_PNG_COMPRESSION, quality]

    ret, buf = cv2.imencode(img_fmt, img, encode_params)
    assert ret, 'failed encoding image'
    return pack(header, buf.tostring())
项目:visual_mpc    作者:febert    | 项目源码 | 文件源码
def _save_img_local(self, i_save):

        pref = self.instance_type

        #saving image
        # saving the full resolution image
        if self.ltob.img_cv2 is not None:
            image_name = self.image_folder+ "/" + pref + "_full_cropped_im{0}".format(str(i_save).zfill(2))
            image_name += "_time{1}.jpg".format(self.ltob.tstamp_img)

            cv2.imwrite(image_name, self.ltob.img_cv2, [int(cv2.IMWRITE_JPEG_QUALITY), 80])
        else:
            raise ValueError('img_cv2 no data received')

        # saving the cropped and downsized image
        if self.ltob.img_cropped is not None:
            image_name = self.image_folder + "/" + pref +"_cropped_im{0}_time{1}.png".format(i_save, self.ltob.tstamp_img)
            cv2.imwrite(image_name, self.ltob.img_cropped, [cv2.IMWRITE_PNG_STRATEGY_DEFAULT,1])
            print 'saving small image to ', image_name
        else:
            raise ValueError('img_cropped no data received')

        # saving the depth data
        # saving the cropped depth data in a Pickle file
        if self.ltob.d_img_cropped_npy is not None:
            file = self.depth_image_folder + "/" + pref +"_depth_im{0}_time{1}.pkl".format(i_save, self.ltob.tstamp_d_img)
            cPickle.dump(self.ltob.d_img_cropped_npy, open(file, 'wb'))
        else:
            raise ValueError('d_img_cropped_npy no data received')

        # saving downsampled 8bit images
        if self.ltob.d_img_cropped_8bit is not None:
            image_name = self.depth_image_folder + "/" + pref + "_cropped_depth_im{0}_time{1}.png".format(i_save, self.ltob.tstamp_d_img)
            cv2.imwrite(image_name, self.ltob.d_img_cropped_8bit, [cv2.IMWRITE_PNG_STRATEGY_DEFAULT, 1])
        else:
            raise ValueError('d_img_cropped_8bit no data received')

        self.t_finish_save.append(rospy.get_time())
        if i_save == (self.state_sequence_length-1):
            with open(self.image_folder+'/{}_snapshot_timing.pkl'.format(pref), 'wb') as f:
                dict = {'t_finish_save': self.t_finish_save }
                if pref == 'aux1':
                    dict['t_get_request'] = self.t_get_request
                cPickle.dump(dict, f)
项目:video-action-recognition    作者:ap916    | 项目源码 | 文件源码
def writeOpticalFlow(path,filename,w,h,c):
    count=0
    try:
        cap = cv2.VideoCapture(path+'/'+filename)
        ret, frame1 = cap.read()

        if frame1==None:
            return count

        frame1 = cv2.resize(frame1, (w,h))
        prvs = cv2.cvtColor(frame1,cv2.COLOR_BGR2GRAY)

        if not os.path.isdir("../dataset/of_images"): os.mkdir("of_images")
        folder = '../dataset/of_images'+'/'+filename+'/'
        dir = os.path.dirname(folder)
        os.mkdir(dir)

        while(1):
            ret, frame2 = cap.read()

            if frame2 is None:
                break
            count+=1
            if count%5==0:
                print (filename+':' +str(c)+'-'+str(count))

                frame2 = cv2.resize(frame2, (w,h))
                next = cv2.cvtColor(frame2,cv2.COLOR_BGR2GRAY)

                flow = cv2.calcOpticalFlowFarneback(prvs,next, None, 0.5, 3, 15, 3, 5, 1.2, 0)

                horz = cv2.normalize(flow[...,0], None, 0, 255, cv2.NORM_MINMAX)
                vert = cv2.normalize(flow[...,1], None, 0, 255, cv2.NORM_MINMAX)
                horz = horz.astype('uint8')
                vert = vert.astype('uint8')

                cv2.imwrite(folder+'h'+str(count)+'_'+filename+'.jpg',horz,[int(cv2.IMWRITE_JPEG_QUALITY), 90])
                cv2.imwrite(folder+'v'+str(count)+'_'+filename+'.jpg',vert,[int(cv2.IMWRITE_JPEG_QUALITY), 90])

                prvs = next

        cap.release()
        cv2.destroyAllWindows()
        return count
    except Exception as e:
        return count
项目:video-action-recognition    作者:ap916    | 项目源码 | 文件源码
def writeOpticalFlow(path,filename,w,h,c):
    count=0
    try:
        cap = cv2.VideoCapture(path+'/'+filename)
        ret, frame1 = cap.read()

        if frame1==None:
            return count

        frame1 = cv2.resize(frame1, (w,h))
        prvs = cv2.cvtColor(frame1,cv2.COLOR_BGR2GRAY)

        if not os.path.isdir("../dataset/of_images"): os.mkdir("of_images")
        folder = '../dataset/of_images'+'/'+filename+'/'
        dir = os.path.dirname(folder)
        os.mkdir(dir)

        while(1):
            ret, frame2 = cap.read()

            if frame2 is None:
                break
            count+=1
            if count%5==0:
                print (filename+':' +str(c)+'-'+str(count))

                frame2 = cv2.resize(frame2, (w,h))
                next = cv2.cvtColor(frame2,cv2.COLOR_BGR2GRAY)

                flow = cv2.calcOpticalFlowFarneback(prvs,next, None, 0.5, 3, 15, 3, 5, 1.2, 0)

                horz = cv2.normalize(flow[...,0], None, 0, 255, cv2.NORM_MINMAX)
                vert = cv2.normalize(flow[...,1], None, 0, 255, cv2.NORM_MINMAX)
                horz = horz.astype('uint8')
                vert = vert.astype('uint8')

                cv2.imwrite(folder+'h'+str(count)+'_'+filename+'.jpg',horz,[int(cv2.IMWRITE_JPEG_QUALITY), 90])
                cv2.imwrite(folder+'v'+str(count)+'_'+filename+'.jpg',vert,[int(cv2.IMWRITE_JPEG_QUALITY), 90])

                prvs = next

        cap.release()
        cv2.destroyAllWindows()
        return count
    except Exception as e:
        return count
项目:Video-Classification-2-Stream-CNN    作者:wadhwasahil    | 项目源码 | 文件源码
def writeOpticalFlow(path,filename,w,h,c):
    count=0
    try:
        cap = cv2.VideoCapture(path+'/'+filename)
        ret, frame1 = cap.read()

        if frame1==None:
            return count

        frame1 = cv2.resize(frame1, (w,h))
        prvs = cv2.cvtColor(frame1,cv2.COLOR_BGR2GRAY)

        folder = './of_images'+'/'+filename+'/'
        dir = os.path.dirname(folder)
        os.mkdir(dir)

        while(1):
            ret, frame2 = cap.read()

            if frame2==None:
                break
            count+=1
            if count%5==0:
                print (filename+':' +str(c)+'-'+str(count))

                frame2 = cv2.resize(frame2, (w,h))
                next = cv2.cvtColor(frame2,cv2.COLOR_BGR2GRAY)

                flow = cv2.calcOpticalFlowFarneback(prvs,next, None, 0.5, 3, 15, 3, 5, 1.2, 0)

                horz = cv2.normalize(flow[...,0], None, 0, 255, cv2.NORM_MINMAX)
                vert = cv2.normalize(flow[...,1], None, 0, 255, cv2.NORM_MINMAX)
                horz = horz.astype('uint8')
                vert = vert.astype('uint8')

                cv2.imwrite(folder+'h'+str(count)+'_'+filename+'.jpg',horz,[int(cv2.IMWRITE_JPEG_QUALITY), 90])
                cv2.imwrite(folder+'v'+str(count)+'_'+filename+'.jpg',vert,[int(cv2.IMWRITE_JPEG_QUALITY), 90])

                prvs = next

        cap.release()
        cv2.destroyAllWindows()
        return count
    except Exception,e:
        print e
        return count