本文整理汇总了Python中cv2.imwrite方法的典型用法代码示例。如果您正苦于以下问题:Python cv2.imwrite方法的具体用法?Python cv2.imwrite怎么用?Python cv2.imwrite使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cv2
的用法示例。
在下文中一共展示了cv2.imwrite方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import imwrite [as 别名]
def main():
imagePath = "img.jpg"
img = cv2.imread(imagePath)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
generate_histogram(gray)
cv2.imwrite("before.jpg", gray)
gray = cv2.equalizeHist(gray)
generate_histogram(gray)
cv2.imwrite("after.jpg",gray)
return 0
示例2: _lapulaseDetection
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import imwrite [as 别名]
def _lapulaseDetection(self, imgName):
"""
:param strdir: 文件所在的目录
:param name: 文件名称
:return: 检测模糊后的分数
"""
# step1: 预处理
img2gray, reImg = self.preImgOps(imgName)
# step2: laplacian算子 获取评分
resLap = cv2.Laplacian(img2gray, cv2.CV_64F)
score = resLap.var()
print("Laplacian %s score of given image is %s", str(score))
# strp3: 绘制图片并保存 不应该写在这里 抽象出来 这是共有的部分
newImg = self._drawImgFonts(reImg, str(score))
newDir = self.strDir + "/_lapulaseDetection_/"
if not os.path.exists(newDir):
os.makedirs(newDir)
newPath = newDir + imgName
# 显示
cv2.imwrite(newPath, newImg) # 保存图片
cv2.imshow(imgName, newImg)
cv2.waitKey(0)
# step3: 返回分数
return score
示例3: saveimageWithMask
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import imwrite [as 别名]
def saveimageWithMask(img, outname, mask_poly):
dstimg = copy.deepcopy(img)
for mask in mask_poly:
bound = mask.bounds
if (len(bound) < 4):
continue
xmin, ymin, xmax, ymax = bound[0], bound[1], bound[2], bound[3]
for x in range(int(xmin), int(xmax)):
for y in range(int(ymin), int(ymax)):
point = shgeo.Point(x, y)
if point.within(mask):
#print('withing')
dstimg[int(y)][int(x)] = 0
cv2.imwrite(outname, dstimg)
示例4: test
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import imwrite [as 别名]
def test(test_loader, model, logger=None, Writer=None):
model.eval()
with torch.no_grad():
for its, (img_line, img_noise) in enumerate(test_loader):
img_line = img_line.cuda() if torch.cuda.is_available() else img_line
img_noise = img_noise.cuda() if torch.cuda.is_available() else img_noise
g_results = model(torch.cat((img_line, img_noise), 1))
for i in range(img_line.shape[0]):
img_line_test = img_line[i].cpu().numpy().transpose((1,2,0)) * 255
img_line_test = img_line_test.squeeze()
cv2.imwrite((cfg.PATH.RES_TEST+"line_{}.jpg".format(i+its)), img_line_test)
img_res_test = g_results[i].cpu().numpy().transpose((1,2,0)) * 255
cv2.imwrite((cfg.PATH.RES_TEST+"res_{}.jpg".format(i+its)), img_res_test)
print("{}/{}".format(i+its,its_num))
示例5: convert_images2bmp
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import imwrite [as 别名]
def convert_images2bmp():
# cv2.imread() jpg at 230 img/s, *.bmp at 400 img/s
for path in ['../coco/images/val2014/', '../coco/images/train2014/']:
folder = os.sep + Path(path).name
output = path.replace(folder, folder + 'bmp')
if os.path.exists(output):
shutil.rmtree(output) # delete output folder
os.makedirs(output) # make new output folder
for f in tqdm(glob.glob('%s*.jpg' % path)):
save_name = f.replace('.jpg', '.bmp').replace(folder, folder + 'bmp')
cv2.imwrite(save_name, cv2.imread(f))
for label_path in ['../coco/trainvalno5k.txt', '../coco/5k.txt']:
with open(label_path, 'r') as file:
lines = file.read()
lines = lines.replace('2014/', '2014bmp/').replace('.jpg', '.bmp').replace(
'/Users/glennjocher/PycharmProjects/', '../')
with open(label_path.replace('5k', '5k_bmp'), 'w') as file:
file.write(lines)
示例6: visual
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import imwrite [as 别名]
def visual(title, X, activation):
'''create a grid of images and save it as a final image
title : grid image name
X : array of images
'''
assert len(X.shape) == 4
X = X.transpose((0, 2, 3, 1))
if activation == 'sigmoid':
X = np.clip((X)*(255.0), 0, 255).astype(np.uint8)
elif activation == 'tanh':
X = np.clip((X+1.0)*(255.0/2.0), 0, 255).astype(np.uint8)
n = np.ceil(np.sqrt(X.shape[0]))
buff = np.zeros((int(n*X.shape[1]), int(n*X.shape[2]), int(X.shape[3])), dtype=np.uint8)
for i, img in enumerate(X):
fill_buf(buff, i, img, X.shape[1:3])
cv2.imwrite('%s.jpg' % (title), buff)
示例7: crop_images_random
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import imwrite [as 别名]
def crop_images_random(path='../images/', scale=0.50): # from utils.utils import *; crop_images_random()
# crops images into random squares up to scale fraction
# WARNING: overwrites images!
for file in tqdm(sorted(glob.glob('%s/*.*' % path))):
img = cv2.imread(file) # BGR
if img is not None:
h, w = img.shape[:2]
# create random mask
a = 30 # minimum size (pixels)
mask_h = random.randint(a, int(max(a, h * scale))) # mask height
mask_w = mask_h # mask width
# box
xmin = max(0, random.randint(0, w) - mask_w // 2)
ymin = max(0, random.randint(0, h) - mask_h // 2)
xmax = min(w, xmin + mask_w)
ymax = min(h, ymin + mask_h)
# apply random color mask
cv2.imwrite(file, img[ymin:ymax, xmin:xmax])
示例8: on_epoch_end
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import imwrite [as 别名]
def on_epoch_end(self, epoch, logs=None):
if self.tiny:
anchors = yolo_tiny_anchors
masks = yolo_tiny_anchor_masks
else:
anchors = yolo_anchors
masks = yolo_anchor_masks
model = make_eval_model_from_trained_model(self.model, anchors, masks)
epoch_dir = os.path.join(self.result_dir, str(epoch))
os.makedirs(epoch_dir)
for batch, (images, labels) in enumerate(self.dataset):
images = images.numpy()
for i in range(images.shape[0]):
boxes, scores, classes = model.predict(images[i:i + 1, ...])
img_for_this = (images[i, ...] * 255).astype(np.uint8)
boxes_for_this, scores_for_this, classes_for_this = boxes[0, ...], scores[0, ...], classes[0, ...]
img_for_this = draw_outputs(img_for_this, (boxes_for_this, scores_for_this, classes_for_this))
cv2.imwrite(os.path.join(epoch_dir, '{0}.jpg'.format(uuid.uuid4())), img_for_this)
if batch == self.num_batches:
break
示例9: _blurDetection
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import imwrite [as 别名]
def _blurDetection(self, imgName):
# step 1 图像的预处理
img2gray, reImg = self.preImgOps(imgName)
imgMat=self._imageToMatrix(img2gray)/255.0
x, y = imgMat.shape
score = 0
for i in range(x - 2):
for j in range(y - 2):
score += (imgMat[i + 2, j] - imgMat[i, j]) ** 2
# step3: 绘制图片并保存 不应该写在这里 抽象出来 这是共有的部分
score=score/10
newImg = self._drawImgFonts(reImg, str(score))
newDir = self.strDir + "/_blurDetection_/"
if not os.path.exists(newDir):
os.makedirs(newDir)
newPath = newDir + imgName
cv2.imwrite(newPath, newImg) # 保存图片
cv2.imshow(imgName, newImg)
cv2.waitKey(0)
return score
示例10: _SMDDetection
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import imwrite [as 别名]
def _SMDDetection(self, imgName):
# step 1 图像的预处理
img2gray, reImg = self.preImgOps(imgName)
f=self._imageToMatrix(img2gray)/255.0
x, y = f.shape
score = 0
for i in range(x - 1):
for j in range(y - 1):
score += np.abs(f[i+1,j]-f[i,j])+np.abs(f[i,j]-f[i+1,j])
# strp3: 绘制图片并保存 不应该写在这里 抽象出来 这是共有的部分
score=score/100
newImg = self._drawImgFonts(reImg, str(score))
newDir = self.strDir + "/_SMDDetection_/"
if not os.path.exists(newDir):
os.makedirs(newDir)
newPath = newDir + imgName
cv2.imwrite(newPath, newImg) # 保存图片
cv2.imshow(imgName, newImg)
cv2.waitKey(0)
return score
示例11: _SMD2Detection
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import imwrite [as 别名]
def _SMD2Detection(self, imgName):
"""
灰度方差乘积
:param imgName:
:return:
"""
# step 1 图像的预处理
img2gray, reImg = self.preImgOps(imgName)
f=self._imageToMatrix(img2gray)/255.0
x, y = f.shape
score = 0
for i in range(x - 1):
for j in range(y - 1):
score += np.abs(f[i+1,j]-f[i,j])*np.abs(f[i,j]-f[i,j+1])
# strp3: 绘制图片并保存 不应该写在这里 抽象出来 这是共有的部分
score=score
newImg = self._drawImgFonts(reImg, str(score))
newDir = self.strDir + "/_SMD2Detection_/"
if not os.path.exists(newDir):
os.makedirs(newDir)
newPath = newDir + imgName
cv2.imwrite(newPath, newImg) # 保存图片
cv2.imshow(imgName, newImg)
cv2.waitKey(0)
return score
示例12: _Variance
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import imwrite [as 别名]
def _Variance(self, imgName):
"""
灰度方差乘积
:param imgName:
:return:
"""
# step 1 图像的预处理
img2gray, reImg = self.preImgOps(imgName)
f = self._imageToMatrix(img2gray)
# strp3: 绘制图片并保存 不应该写在这里 抽象出来 这是共有的部分
score = np.var(f)
newImg = self._drawImgFonts(reImg, str(score))
newDir = self.strDir + "/_Variance_/"
if not os.path.exists(newDir):
os.makedirs(newDir)
newPath = newDir + imgName
cv2.imwrite(newPath, newImg) # 保存图片
cv2.imshow(imgName, newImg)
cv2.waitKey(0)
return score
示例13: make_edge_smooth
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import imwrite [as 别名]
def make_edge_smooth(dataset_name, img_size) :
check_folder('./dataset/{}/{}'.format(dataset_name, 'trainB_smooth'))
file_list = glob('./dataset/{}/{}/*.*'.format(dataset_name, 'trainB'))
save_dir = './dataset/{}/trainB_smooth'.format(dataset_name)
kernel_size = 5
kernel = np.ones((kernel_size, kernel_size), np.uint8)
gauss = cv2.getGaussianKernel(kernel_size, 0)
gauss = gauss * gauss.transpose(1, 0)
for f in tqdm(file_list) :
file_name = os.path.basename(f)
bgr_img = cv2.imread(f)
gray_img = cv2.imread(f, 0)
bgr_img = cv2.resize(bgr_img, (img_size, img_size))
pad_img = np.pad(bgr_img, ((2, 2), (2, 2), (0, 0)), mode='reflect')
gray_img = cv2.resize(gray_img, (img_size, img_size))
edges = cv2.Canny(gray_img, 100, 200)
dilation = cv2.dilate(edges, kernel)
gauss_img = np.copy(bgr_img)
idx = np.where(dilation != 0)
for i in range(np.sum(dilation != 0)):
gauss_img[idx[0][i], idx[1][i], 0] = np.sum(
np.multiply(pad_img[idx[0][i]:idx[0][i] + kernel_size, idx[1][i]:idx[1][i] + kernel_size, 0], gauss))
gauss_img[idx[0][i], idx[1][i], 1] = np.sum(
np.multiply(pad_img[idx[0][i]:idx[0][i] + kernel_size, idx[1][i]:idx[1][i] + kernel_size, 1], gauss))
gauss_img[idx[0][i], idx[1][i], 2] = np.sum(
np.multiply(pad_img[idx[0][i]:idx[0][i] + kernel_size, idx[1][i]:idx[1][i] + kernel_size, 2], gauss))
cv2.imwrite(os.path.join(save_dir, file_name), gauss_img)
示例14: loop2
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import imwrite [as 别名]
def loop2(self,text,w=1280,h=720):
cap = cv2.VideoCapture(int(text))
cap.set(6 ,cv2.VideoWriter_fourcc('M', 'J', 'P', 'G') );
global capnum2
capnum2 = int(text)
cap.set(3,w);
cap.set(4,h);
global update2
update2 = 1
global shotmark2
while (update2 == 1):
ret, frame = cap.read()
if shotmark2 == 1:
fn = self.lineEdit.text()
name = "photo/2_"+fn + "video.jpg"
if os.path.exists(name):
name = "photo/2_" + fn + "video"+str(int(time.time()))+".jpg"
cv2.imwrite(name, frame)
shotmark2 = 0
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
self.original2_image.updateImage(frame)
# cap.release()
cv_img_rgb = np.zeros((700,700,3))
self.original2_image.updateImage(cv_img_rgb)
示例15: degrade_images_in_folder
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import imwrite [as 别名]
def degrade_images_in_folder(
folder,
dst_folder_suffix,
LIGHTDOWN=True,
UNBALANCECOLOR=True,):
import os
js = os.listdir(folder)
dst_folder = folder + '-' + dst_folder_suffix
try:
os.mkdir(dst_folder)
except:
print('dir exist!')
print('in ' + dst_folder)
num = 3
for j in js:
img = cv2.imread(folder + '/' + j) / 255.
if LIGHTDOWN:
for _ in range(num - 1):
out = pow(img, np.random.uniform(0.4, 0.6)) * np.random.uniform(
0.25, 0.5)
cv2.imwrite(dst_folder + '/' + ('L%d-' % _) + j, out * 255.)
out = img * img
out = out * (1.0 / out.max())
cv2.imwrite(dst_folder + '/' + ('L%d-' % num) + j, out * 255.)
if UNBALANCECOLOR:
filter = WB2()
outs = np.array([img] * num)
features = np.abs(np.random.rand(num, 3))
for _, out in enumerate(
filter.process(outs, filter.filter_param_regressor(features))):
# print out.max()
out /= out.max()
out *= np.random.uniform(0.7, 1)
cv2.imwrite(dst_folder + '/' + ('C%d-' % _) + j, out * 255.)