当前位置: 首页>>代码示例>>Python>>正文


Python cv2.IMWRITE_PNG_COMPRESSION属性代码示例

本文整理汇总了Python中cv2.IMWRITE_PNG_COMPRESSION属性的典型用法代码示例。如果您正苦于以下问题:Python cv2.IMWRITE_PNG_COMPRESSION属性的具体用法?Python cv2.IMWRITE_PNG_COMPRESSION怎么用?Python cv2.IMWRITE_PNG_COMPRESSION使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在cv2的用法示例。


在下文中一共展示了cv2.IMWRITE_PNG_COMPRESSION属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: process_image

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import IMWRITE_PNG_COMPRESSION [as 别名]
def process_image(fid):
    fid = fid + '.png'

    used_msks = []

    for pr_f in pred_folders:
        msk1 = cv2.imread(path.join('/wdata/', pr_f, '{0}.png'.format(fid.split('.')[0])), cv2.IMREAD_UNCHANGED)
        used_msks.append(msk1)

    msk = np.zeros_like(used_msks[0], dtype='float')

    for i in range(len(pred_folders)):
        p = used_msks[i]
        msk += (coefs[i] * p.astype('float'))
    msk /= np.sum(coefs)

    cv2.imwrite(path.join('/wdata/merged_oof', fid), msk.astype('uint8'), [cv2.IMWRITE_PNG_COMPRESSION, 9]) 
开发者ID:SpaceNetChallenge,项目名称:SpaceNet_Off_Nadir_Solutions,代码行数:19,代码来源:merge_oof.py

示例2: process_image

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import IMWRITE_PNG_COMPRESSION [as 别名]
def process_image(img_id):
    if 'Pan-Sharpen_' in img_id:
        img_id = img_id.split('Pan-Sharpen_')[1]
    img = io.imread(path.join(test_dir, '_'.join(img_id.split('_')[:4]), 'Pan-Sharpen', 'Pan-Sharpen_' + img_id+'.tif'))
    nir = img[:, :, 3:]
    img = img[:, :, :3]
    np.clip(img, None, threshold, out=img)
    img = np.floor_divide(img, threshold / 255).astype('uint8')
    cv2.imwrite(path.join(test_png, img_id + '.png'), img, [cv2.IMWRITE_PNG_COMPRESSION, 9])

    img2 = io.imread(path.join(test_dir, '_'.join(img_id.split('_')[:4]), 'MS', 'MS_' + img_id+'.tif'))
    img2 = np.rollaxis(img2, 0, 3)
    img2 = cv2.resize(img2, (900, 900), interpolation=cv2.INTER_LANCZOS4)
    
    img_0_3_5 = (np.clip(img2[..., [0, 3, 5]], None, (2000, 3000, 3000)) / (np.array([2000, 3000, 3000]) / 255)).astype('uint8')
    cv2.imwrite(path.join(test_png2, img_id + '.png'), img_0_3_5, [cv2.IMWRITE_PNG_COMPRESSION, 9])
    
    pan = io.imread(path.join(test_dir, '_'.join(img_id.split('_')[:4]), 'PAN', 'PAN_' + img_id+'.tif'))
    pan = pan[..., np.newaxis]
    img_pan_6_7 = np.concatenate([pan, img2[..., 7:], nir], axis=2)
    img_pan_6_7 = (np.clip(img_pan_6_7, None, (3000, 5000, 5000)) / (np.array([3000, 5000, 5000]) / 255)).astype('uint8')
    cv2.imwrite(path.join(test_png3, img_id + '.png'), img_pan_6_7, [cv2.IMWRITE_PNG_COMPRESSION, 9]) 
开发者ID:SpaceNetChallenge,项目名称:SpaceNet_Off_Nadir_Solutions,代码行数:24,代码来源:convert_test.py

示例3: save_img

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import IMWRITE_PNG_COMPRESSION [as 别名]
def save_img(img, filename):

    print("Save %s" %filename)

    if img.ndim == 3:
        img = img[:, :, ::-1] ### RGB to BGR
    
    ## clip to [0, 1]
    img = np.clip(img, 0, 1)

    ## quantize to [0, 255]
    img = np.uint8(img * 255.0)

    cv2.imwrite(filename, img, [cv2.IMWRITE_PNG_COMPRESSION, 0])


######################################################################################
##  Flow utility
###################################################################################### 
开发者ID:zllrunning,项目名称:video-object-removal,代码行数:21,代码来源:utils.py

示例4: shape_chosen

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import IMWRITE_PNG_COMPRESSION [as 别名]
def shape_chosen(self, event):
        tmp = self.get_item_text(event.GetItem())
        if not tmp:
            return
        else:
            chosen_shape = ('the shape is ' + tmp)
            set_goal(self.engine, chosen_shape)
            results, matched_facts, hit_rules = main_run(self.engine)
            source_image = cv2.imread(self.pic_path)
            detection_image = np.zeros(source_image.shape, np.uint8)
            draw_lines(detection_image, matched_facts, self.contour_num)
            cv2.imwrite('detection.png', detection_image, [int(cv2.IMWRITE_PNG_COMPRESSION), 0])
            self.show_picture('detection.png', (420, 30))
            self.resultText.Clear()
            self.resultText.WriteText(get_result(results))
            self.matchedFactText.Clear()
            self.matchedFactText.WriteText(get_matched_facts(matched_facts, self.contour_num))
            self.hitRuleText.Clear()
            self.hitRuleText.WriteText(get_hit_rules(hit_rules, self.contour_num)) 
开发者ID:Sorosliu1029,项目名称:Rule-based_Expert_System,代码行数:21,代码来源:main_frame.py

示例5: writer

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import IMWRITE_PNG_COMPRESSION [as 别名]
def writer():
    # Writer is run in a separate thread, so that writing is concurrent
    # to taking the pictures.
    global q, job_finished, still_writing
    write_time = Stopwatch()
    #writeParams = (int(cv2.IMWRITE_PNG_COMPRESSION),7)
    while not job_finished:
	still_writing = True
	while not q.empty():
	    write_time.start()
            fn,img = q.get()
	    try:
                cv2.imwrite(fn,img, fileSaveParams)
                t=write_time.stop()
                print('Written {} in {:.02f} secs'.format(fn,t))
	    except:
		t=write_time.stop()
		print('Failed to write {} in {:.02f} secs'.format(fn,t))
    # Finished all jobs and queue is empty
    still_writing = False 
开发者ID:Alexamder,项目名称:rpitelecine,代码行数:22,代码来源:tc-run.py

示例6: pack_img

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import IMWRITE_PNG_COMPRESSION [as 别名]
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. See more detail in ``IRHeader``.
    img : numpy.ndarray
        Image to be packed.
    quality : int
        Quality for JPEG encoding in range 1-100, or compression for PNG encoding in range 1-9.
    img_fmt : str
        Encoding of the image (.jpg for JPEG, .png for PNG).

    Returns
    -------
    s : str
        The packed string.

    Examples
    --------
    >>> label = 4 # label can also be a 1-D array, for example: label = [1,2,3]
    >>> id = 2574
    >>> header = mx.recordio.IRHeader(0, label, id, 0)
    >>> img = cv2.imread('test.jpg')
    >>> packed_s = mx.recordio.pack_img(header, img)
    """
    assert cv2 is not None
    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 to encode image'
    return pack(header, buf.tostring()) 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:42,代码来源:recordio.py

示例7: saveTensorToImages

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import IMWRITE_PNG_COMPRESSION [as 别名]
def saveTensorToImages(t, idxs, save_to_path):
    
    if os.path.exists(save_to_path)==False:
        os.mkdir(save_to_path)
    
    for i in range(t.size(0)):
        im = t[i,:,:,:].detach().data.cpu().numpy() 
        im = np.transpose(im, (1,2,0)).astype(np.uint16)
        cv2.imwrite(os.path.join(save_to_path, str(idxs[i].data.cpu().numpy()).zfill(10)+'.png'), im, [cv2.IMWRITE_PNG_COMPRESSION, 4] ) 
开发者ID:abdo-eldesokey,项目名称:nconv,代码行数:11,代码来源:saveTensorToImages.py

示例8: save_img

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import IMWRITE_PNG_COMPRESSION [as 别名]
def save_img(img, img_name):
    save_img = img.squeeze().clamp(0, 1).numpy().transpose(1,2,0)

    # save img    
    save_fn = 'im'+img_name+'_'+opt.model_type+opt.prefix+'.png'
    cv2.imwrite(save_fn, cv2.cvtColor(save_img*255, cv2.COLOR_BGR2RGB),  [cv2.IMWRITE_PNG_COMPRESSION, 0]) 
开发者ID:alterzero,项目名称:STARnet,代码行数:8,代码来源:main.py

示例9: save_img

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import IMWRITE_PNG_COMPRESSION [as 别名]
def save_img(img, d_dir,img_name, pred_flag):
    save_img = img.squeeze().clamp(0, 1).numpy().transpose(1,2,0)
    filename = os.path.splitext(img_name)

    # save img
    save_dir=os.path.join(opt.output, d_dir)
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)
        
    if pred_flag:
        save_fn = save_dir +'/'+ filename[0]+'_'+opt.model_type+filename[1]
    else:
        save_fn = save_dir +'/'+ img_name
    cv2.imwrite(save_fn, cv2.cvtColor(save_img*255, cv2.COLOR_BGR2RGB),  [cv2.IMWRITE_PNG_COMPRESSION, 0]) 
开发者ID:alterzero,项目名称:STARnet,代码行数:16,代码来源:eval_star_t_hr.py

示例10: save_img

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import IMWRITE_PNG_COMPRESSION [as 别名]
def save_img(img, img_name):
    save_img = img.squeeze().clamp(0, 1).numpy().transpose(1,2,0)

    # save img    
    save_fn = 'im'+img_name+'_'+opt.model_type+opt.prefix+'_'+opt.train_obj+'.png'
    cv2.imwrite(save_fn, cv2.cvtColor(save_img*255, cv2.COLOR_BGR2RGB),  [cv2.IMWRITE_PNG_COMPRESSION, 0]) 
开发者ID:alterzero,项目名称:STARnet,代码行数:8,代码来源:main_refinement_flow.py

示例11: save_img

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import IMWRITE_PNG_COMPRESSION [as 别名]
def save_img(img, img_name, pred_flag):
    save_img = img.squeeze().clamp(0, 1).numpy().transpose(1,2,0)

    # save img
    save_dir=os.path.join(args.output, args.data_dir, os.path.splitext(args.file_list)[0]+'_'+str(args.upscale_factor)+'x')
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)
        
    if pred_flag:
        save_fn = save_dir +'/'+ img_name+'_'+args.model_type+'F'+str(args.nFrames)+'.png'
    else:
        save_fn = save_dir +'/'+ img_name+'.png'
    cv2.imwrite(save_fn, cv2.cvtColor(save_img*255, cv2.COLOR_BGR2RGB),  [cv2.IMWRITE_PNG_COMPRESSION, 0]) 
开发者ID:amanchadha,项目名称:iSeeBetter,代码行数:15,代码来源:iSeeBetterTest.py

示例12: worker

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import IMWRITE_PNG_COMPRESSION [as 别名]
def worker(path, save_folder, crop_sz, step, thres_sz, compression_level):
    img_name = os.path.basename(path)
    img = cv2.imread(path, cv2.IMREAD_UNCHANGED)

    n_channels = len(img.shape)
    if n_channels == 2:
        h, w = img.shape
    elif n_channels == 3:
        h, w, c = img.shape
    else:
        raise ValueError('Wrong image shape - {}'.format(n_channels))

    h_space = np.arange(0, h - crop_sz + 1, step)
    if h - (h_space[-1] + crop_sz) > thres_sz:
        h_space = np.append(h_space, h - crop_sz)
    w_space = np.arange(0, w - crop_sz + 1, step)
    if w - (w_space[-1] + crop_sz) > thres_sz:
        w_space = np.append(w_space, w - crop_sz)

    index = 0
    for x in h_space:
        for y in w_space:
            index += 1
            if n_channels == 2:
                crop_img = img[x:x + crop_sz, y:y + crop_sz]
            else:
                crop_img = img[x:x + crop_sz, y:y + crop_sz, :]
            crop_img = np.ascontiguousarray(crop_img)
            # var = np.var(crop_img / 255)
            # if var > 0.008:
            #     print(img_name, index_str, var)
            cv2.imwrite(
                os.path.join(save_folder, img_name.replace('.png', '_s{:03d}.png'.format(index))),
                crop_img, [cv2.IMWRITE_PNG_COMPRESSION, compression_level])
    return 'Processing {:s} ...'.format(img_name) 
开发者ID:xinntao,项目名称:BasicSR,代码行数:37,代码来源:extract_subimgs_single.py

示例13: worker

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import IMWRITE_PNG_COMPRESSION [as 别名]
def worker(path, save_folder, mode, compression_level):
    img_name = os.path.basename(path)
    img = cv2.imread(path, cv2.IMREAD_UNCHANGED)  # BGR
    if mode == 'gray':
        img_y = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    else:
        img_y = bgr2ycbcr(img, only_y=True)
    cv2.imwrite(os.path.join(save_folder, img_name), img_y,
                [cv2.IMWRITE_PNG_COMPRESSION, compression_level])
    return 'Processing {:s} ...'.format(img_name) 
开发者ID:xinntao,项目名称:BasicSR,代码行数:12,代码来源:color2gray.py

示例14: map

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import IMWRITE_PNG_COMPRESSION [as 别名]
def map(self, data):
        image = data[self.src]
        image_id = data["image_id"]

        # Prepare output for image based on image_id
        output = image_id.split(os.path.sep)
        dirname = output[:-1]
        if len(dirname) > 0:
            dirname = os.path.join(*dirname)
            dirname = os.path.join(self.path, dirname)
            os.makedirs(dirname, exist_ok=True)
        else:
            dirname = self.path
        filename = f"{output[-1].rsplit('.', 1)[0]}.{self.image_ext}"
        path = os.path.join(dirname, filename)

        if self.image_ext == "jpg":
            cv2.imwrite(path, image,
                        (cv2.IMWRITE_JPEG_QUALITY, self.jpg_quality) if self.jpg_quality else None)
        elif self.image_ext == "png":
            cv2.imwrite(path, image,
                        (cv2.IMWRITE_PNG_COMPRESSION, self.png_compression) if self.png_compression else None)
        else:
            raise Exception("Unsupported image format")

        return data 
开发者ID:jagin,项目名称:detectron2-pipeline,代码行数:28,代码来源:save_image.py

示例15: generateAnomalyMapTiles

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import IMWRITE_PNG_COMPRESSION [as 别名]
def generateAnomalyMapTiles(pre_mask_dir, post_mask_dir, street_map_dir, output_dir, street_map_file_ext = '.png'):
	"""
		Parameters:
			pre_mask_dir: directory containing the pre event segmentation mask tiles.
			post_mask_dir: directory containing the post event segmentation mask tiles.
			street_map_dir: directory containing steet map tiles.
			output_dir: directory where new anomaly tiles are saved.
			street_map_file_ext: file extension of the street map tiles. default is .png.
	"""
	pre_file_list = _image_file_list(pre_mask_dir)
	for pre_file in tqdm(pre_file_list):
		post_file = pre_file.replace(pre_mask_dir, post_mask_dir, 1)
		if os.path.exists(post_file):
			street_file = pre_file.replace(pre_mask_dir, street_map_dir, 1)
			street_file = os.path.splitext(street_file)[0] + street_map_file_ext
			anomaly_img = generate_anomaly_img(pre_file, post_file, street_file)
			output_file = pre_file.replace(pre_mask_dir, output_dir, 1)
			# must save in a format that supports alpha transparency (e.g. PNG or WEBP)
			output_file = os.path.splitext(output_file)[0]+'.png'
			print('output file: {}'.format(output_file))
			makedirs(os.path.dirname(output_file))
			cv2.imwrite(output_file, anomaly_img, [cv2.IMWRITE_PNG_COMPRESSION, 9]) # max compression
		else:
			print('no matching post image: {}'.format(post_file))
	print('map tiles generation complete')

# execution starts here. command line args processing. 
开发者ID:jackkwok,项目名称:neural-road-inspector,代码行数:29,代码来源:anomalyMapGen.py


注:本文中的cv2.IMWRITE_PNG_COMPRESSION属性示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。