本文整理匯總了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.)