火山引擎图像超分使用

官网对超分能力的介绍:https://www.volcengine.com/docs/86081/1660419

快速入门里面对于如何获得key已经有详细介绍了:https://www.volcengine.com/docs/86081/1660009

问题出现在获得这些之后,如何进行后续的相关操作,也就是上传图片,并返回得到处理过后的图片。

文档中心有一个基础的教程https://www.volcengine.com/docs/6444/1390583,我是用的是python的版本

为了传入url,我使用了gitee作为媒介,当然使用github也是一样的,但是我这里github不稳定,就使用git了

接下来遇到的第一个问题是图片解码一直出错,这个我尝试修改了图片的格式也没有解决,后来莫名其妙就自己好了,我都怀疑是不是因为服务开通的时间有延迟?

第二个问题就是官方给的例子,拿到最后的是base64的码流,当然可以使用网页在线转(我一开始就是这么干的),https://www.base64decode.org/

这样到底不方便,后面从网上搜了一段直接能够转化的python代码,和原始的代码拼到一起,就可以直接将处理的图像保存到本地了。

下面直接附上完整代码,当然key已经被我删除了。

python 复制代码
import json
import sys
import os
import base64
import datetime
import hashlib
import hmac
import requests


method = 'POST'
host = 'visual.volcengineapi.com'
region = 'cn-north-1'
endpoint = 'https://visual.volcengineapi.com'
service = 'cv'

def sign(key, msg):
	return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()

def getSignatureKey(key, dateStamp, regionName, serviceName):
	kDate = sign(key.encode('utf-8'), dateStamp)
	kRegion = sign(kDate, regionName)
	kService = sign(kRegion, serviceName)
	kSigning = sign(kService, 'request')
	return kSigning

def formatQuery(parameters):
	request_parameters_init = ''
	for key in sorted(parameters):
		request_parameters_init += key + '=' + parameters[key] + '&'
	request_parameters = request_parameters_init[:-1]
	return request_parameters

def save_base64_image(base64_data, output_path):
# 移除可能的前缀
	if "base64," in base64_data:
		base64_data = base64_data.split("base64,")[1]

	# 解码并保存图片
	with open(output_path, "wb") as f:
		f.write(base64.b64decode(base64_data))

	print(f"图片已保存至 {output_path}")
			
def signV4Request(access_key, secret_key, service, req_query, req_body):
	if access_key is None or secret_key is None:
		print('No access key is available.')
		sys.exit()

	t = datetime.datetime.utcnow()
	current_date = t.strftime('%Y%m%dT%H%M%SZ')
	# current_date = '20210818T095729Z'
	datestamp = t.strftime('%Y%m%d')  # Date w/o time, used in credential scope
	canonical_uri = '/'
	canonical_querystring = req_query
	signed_headers = 'content-type;host;x-content-sha256;x-date'
	payload_hash = hashlib.sha256(req_body.encode('utf-8')).hexdigest()
	content_type = 'application/json'
	canonical_headers = 'content-type:' + content_type + '\n' + 'host:' + host + \
		'\n' + 'x-content-sha256:' + payload_hash + \
		'\n' + 'x-date:' + current_date + '\n'
	canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + \
		'\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash
	# print(canonical_request)
	algorithm = 'HMAC-SHA256'
	credential_scope = datestamp + '/' + region + '/' + service + '/' + 'request'
	string_to_sign = algorithm + '\n' + current_date + '\n' + credential_scope + '\n' + hashlib.sha256(
		canonical_request.encode('utf-8')).hexdigest()
	# print(string_to_sign)
	signing_key = getSignatureKey(secret_key, datestamp, region, service)
	# print(signing_key)
	signature = hmac.new(signing_key, (string_to_sign).encode(
		'utf-8'), hashlib.sha256).hexdigest()
	# print(signature)

	authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + \
		credential_scope + ', ' + 'SignedHeaders=' + \
		signed_headers + ', ' + 'Signature=' + signature
	# print(authorization_header)
	headers = {'X-Date': current_date,
			   'Authorization': authorization_header,
			   'X-Content-Sha256': payload_hash,
			   'Content-Type': content_type
			   }
	# print(headers)

	# ************* SEND THE REQUEST *************
	request_url = endpoint + '?' + canonical_querystring

	print('\nBEGIN REQUEST++++++++++++++++++++++++++++++++++++')
	print('Request URL = ' + request_url)
	try:
		r = requests.post(request_url, headers=headers, data=req_body)
		# print(r.text.type())
		# print(r.text['binary_data_base64'])
	except Exception as err:
		print(f'error occurred: {err}')
		raise
	else:
		print('\nRESPONSE++++++++++++++++++++++++++++++++++++')
		print(f'Response code: {r.status_code}\n')
		# 使用 replace 方法将 \u0026 替换为 &
		resp_str = r.text.replace("\\u0026", "&")
		print(f'Response body: {resp_str}\n')

		content = resp_str.split('"binary_data_base64":[')[1]
		content = content.split('"]},"message"')[0]
		save_base64_image(content, "fig12.jpg")



if __name__ == "__main__":
	# 请求凭证,从访问控制申请
	
	# import base64
	# import requests

	# url = "https://gitee.com/bq2w/pic_paper/raw/master/fig4.jpg"
	# response = requests.get(url)
	# image_base64 = base64.b64encode(response.content).decode("utf-8")
	
	access_key = ''  #your key
	secret_key = ''

	# 请求Query,按照接口文档中填入即可
	query_params = {
		'Action': 'CVProcess',
		'Version': '2022-08-31',
	}
	formatted_query = formatQuery(query_params)

	# 请求Body,按照接口文档中填入即可
	body_params = {
		#"req_key": "lens_vida_nnsr",
		"req_key": "lens_nnsr2_pic_common",
		"image_urls": [
			"https://gitexx.png",
		],
		"model_quality": "MQ",
		"aigc_meta": {
			"producer_id": "1",
		}
	}
	formatted_body = json.dumps(body_params)
	
	signV4Request(access_key, secret_key, service,
				  formatted_query, formatted_body)

别的服务,没有开通,也没有试过,但是就体验来说,怎么说呢,可能自然风景还行,如果是科研照片,还是不太行

相关推荐
Wnq100723 小时前
巡检机器人户外视觉识别困境剖析与自动优化模式构建
图像处理·目标检测·低代码·计算机视觉·目标跟踪·机器人·需求分析
AndrewHZ7 小时前
【图像处理基石】通过立体视觉重建建筑高度:原理、实操与代码实现
图像处理·人工智能·计算机视觉·智慧城市·三维重建·立体视觉·1024程序员节
Antonio91519 小时前
【图像处理】灰度图像与二值化
图像处理·opencv
yanxing.D1 天前
penCV轻松入门_面向python(第七章 图像平滑处理)
图像处理·人工智能·opencv·计算机视觉
Antonio9151 天前
【图像处理】CMKY色彩空间
图像处理
不良人龍木木1 天前
云图-地基云图
图像处理·算法·计算机视觉·1024程序员节
小殊小殊2 天前
【论文笔记】LTX-Video极致速度的视频生成模型
图像处理·人工智能·深度学习
Antonio9152 天前
【图像处理】图像形态学操作
图像处理·人工智能·opencv
AndrewHZ2 天前
【图像处理基石】多光谱图片去噪入门:从概念到Python实操
图像处理·python·计算机视觉·图像去噪·多光谱