cv.imwrite写入图片问题(opencv)

tiaowei9500 2016-07-29 11:15:15

像这样写入图片的话就会报错


但是如果注释掉写入图片的语言,那就可以正常运行:如下



请问这个该怎么办呀
...全文
3014 10 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
hmy-666 2020-03-14
  • 打赏
  • 举报
回复
# 视频分解图片
# 1.load 2.info 3.parse 4.imshow 5.imwrite
import cv2
cap = cv2.VideoCapture("./pop/pop.mp4")
isOpened = cap.isOpened # 判断是否可以打开
print(isOpened)
fps = cap.get(cv2.CAP_PROP_FPS) # 帧率
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) # 获取宽,高
heigth = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
print(fps,width,heigth)
i = 0
while(isOpened):
if i==10:
break
else:
i = i+1
(flag,frame) = cap.read() # 读取每一种的 flag(表示是否读取成功),frame(表示内容)
fileName = 'pop\img'+str(i)+'.jpg' # pop\为写入的文件夹地址,img表示写入的名称
print(fileName)
if flag == True: # 如果读取图片成功
cv2.imwrite(fileName,frame,[cv2.IMWRITE_JPEG_QUALITY,100]) # 写入图片 fileName:图片名称,frame:图片·内容;最后一个表示写入的图片格式
print('写入图片结束!')
hmy-666 2020-03-14
  • 打赏
  • 举报
回复
# 视频分解图片
# 1.load 2.info 3.parse 4.imshow 5.imwrite
import cv2
cap = cv2.VideoCapture("./pop/pop.mp4")
isOpened = cap.isOpened # 判断是否可以打开
print(isOpened)
fps = cap.get(cv2.CAP_PROP_FPS) # 帧率
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) # 获取宽,高
heigth = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
print(fps,width,heigth)
i = 0
while(isOpened):
if i==10:
break
else:
i = i+1
(flag,frame) = cap.read() # 读取每一种的 flag(表示是否读取成功),frame(表示内容)
fileName = 'pop\img'+str(i)+'.jpg' # pop\为写入的文件夹地址,img表示写入的名称
print(fileName)
if flag == True: # 如果读取图片成功
cv2.imwrite(fileName,frame,[cv2.IMWRITE_JPEG_QUALITY,100]) # 写入图片 fileName:图片名称,frame:图片·内容;最后一个表示写入的图片格式
print('写入图片结束!')
qq_41615583 2018-06-06
  • 打赏
  • 举报
回复
您好请问您是怎样解决cv2imwrite出错的问题的,我的也这样,这是我的代码
test.py

# System libs
import os
import datetime
import argparse
from distutils.version import LooseVersion
# Numerical libs
import numpy as np
import torch
import torch.nn as nn
from scipy.io import loadmat
# Our libs
from dataset import TestDataset
from models import ModelBuilder, SegmentationModule
from utils import colorEncode
from lib.nn import user_scattered_collate, async_copy_to
from lib.utils import as_numpy, mark_volatile
import lib.utils.data as torchdata
import cv2


def visualize_result(data, preds, args):
colors = loadmat('data/color150.mat')['colors']
(img, info) = data

# prediction
pred_color = colorEncode(preds, colors)

# aggregate images and save
im_vis = np.concatenate((img, pred_color),
axis=1).astype(np.uint8)

img_name = info.split('/')[-1]
cv2.imwrite(os.path.join(args.result,
img_name.replace('.jpg', '.png')), im_vis)


def test(segmentation_module, loader, args):
segmentation_module.eval()

for i, batch_data in enumerate(loader):
# process data
batch_data = batch_data[0]
segSize = (batch_data['img_ori'].shape[0],
batch_data['img_ori'].shape[1])

img_resized_list = batch_data['img_data']

with torch.no_grad():
pred = torch.zeros(1, args.num_class, segSize[0], segSize[1])

for img in img_resized_list:
feed_dict = batch_data.copy()
feed_dict['img_data'] = img
del feed_dict['img_ori']
del feed_dict['info']
feed_dict = async_copy_to(feed_dict, args.gpu_id)

# forward pass
pred_tmp = segmentation_module(feed_dict, segSize=segSize)
pred = pred + pred_tmp.cpu() / len(args.imgSize)

_, preds = torch.max(pred, dim=1)
preds = as_numpy(preds.squeeze(0))

# visualization
visualize_result(
(batch_data['img_ori'], batch_data['info']),
preds, args)

print('[{}] iter {}'
.format(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), i))


def main(args):
torch.cuda.set_device(args.gpu_id)

# Network Builders
builder = ModelBuilder()
net_encoder = builder.build_encoder(
arch=args.arch_encoder,
fc_dim=args.fc_dim,
weights=args.weights_encoder)
net_decoder = builder.build_decoder(
arch=args.arch_decoder,
fc_dim=args.fc_dim,
num_class=args.num_class,
weights=args.weights_decoder,
use_softmax=True)

crit = nn.NLLLoss(ignore_index=-1)

segmentation_module = SegmentationModule(net_encoder, net_decoder, crit)

# Dataset and Loader
list_test = [{'fpath_img': args.test_img}]
dataset_val = TestDataset(
list_test, args, max_sample=args.num_val)
loader_val = torchdata.DataLoader(
dataset_val,
batch_size=args.batch_size,
shuffle=False,
collate_fn=user_scattered_collate,
num_workers=5,
drop_last=True)

segmentation_module.cuda()

# Main loop
test(segmentation_module, loader_val, args)

print('Inference done!')


if __name__ == '__main__':
assert LooseVersion(torch.__version__) >= LooseVersion('0.4.0'), \
'PyTorch>=0.4.0 is required'

parser = argparse.ArgumentParser()
# Path related arguments
parser.add_argument('--test_img', required=True)
parser.add_argument('--model_path', required=True,
help='folder to model path')
parser.add_argument('--suffix', default='_epoch_20.pth',
help="which snapshot to load")

# Model related arguments
parser.add_argument('--arch_encoder', default='resnet50_dilated8',
help="architecture of net_encoder")
parser.add_argument('--arch_decoder', default='ppm_bilinear_deepsup',
help="architecture of net_decoder")
parser.add_argument('--fc_dim', default=2048, type=int,
help='number of features between encoder and decoder')

# Data related arguments
parser.add_argument('--num_val', default=-1, type=int,
help='number of images to evalutate')
parser.add_argument('--num_class', default=150, type=int,
help='number of classes')
parser.add_argument('--batch_size', default=1, type=int,
help='batchsize. current only supports 1')
parser.add_argument('--imgSize', default=[300, 400, 500, 600],
nargs='+', type=int,
help='list of input image sizes.'
'for multiscale testing, e.g. 300 400 500')
parser.add_argument('--imgMaxSize', default=1000, type=int,
help='maximum input image size of long edge')
parser.add_argument('--padding_constant', default=8, type=int,
help='maxmimum downsampling rate of the network')
parser.add_argument('--segm_downsampling_rate', default=8, type=int,
help='downsampling rate of the segmentation label')

# Misc arguments
parser.add_argument('--result', default='.',
help='folder to output visualization results')
parser.add_argument('--gpu_id', default=0, type=int,
help='gpu_id for evaluation')

args = parser.parse_args()
print(args)

# absolute paths of model weights
args.weights_encoder = os.path.join(args.model_path,
'encoder' + args.suffix)
args.weights_decoder = os.path.join(args.model_path,
'decoder' + args.suffix)

assert os.path.exists(args.weights_encoder) and \
os.path.exists(args.weights_encoder), 'checkpoint does not exitst!'

if not os.path.isdir(args.result):
os.makedirs(args.result)

main(args)
qq_41615583 2018-06-06
  • 打赏
  • 举报
回复
您好请问您是怎样解决cv2imwrite出错的问题的,我的也这样,这是我的代码
test.py

# System libs
import os
import datetime
import argparse
from distutils.version import LooseVersion
# Numerical libs
import numpy as np
import torch
import torch.nn as nn
from scipy.io import loadmat
# Our libs
from dataset import TestDataset
from models import ModelBuilder, SegmentationModule
from utils import colorEncode
from lib.nn import user_scattered_collate, async_copy_to
from lib.utils import as_numpy, mark_volatile
import lib.utils.data as torchdata
import cv2


def visualize_result(data, preds, args):
colors = loadmat('data/color150.mat')['colors']
(img, info) = data

# prediction
pred_color = colorEncode(preds, colors)

# aggregate images and save
im_vis = np.concatenate((img, pred_color),
axis=1).astype(np.uint8)

img_name = info.split('/')[-1]
cv2.imwrite(os.path.join(args.result,
img_name.replace('.jpg', '.png')), im_vis)


def test(segmentation_module, loader, args):
segmentation_module.eval()

for i, batch_data in enumerate(loader):
# process data
batch_data = batch_data[0]
segSize = (batch_data['img_ori'].shape[0],
batch_data['img_ori'].shape[1])

img_resized_list = batch_data['img_data']

with torch.no_grad():
pred = torch.zeros(1, args.num_class, segSize[0], segSize[1])

for img in img_resized_list:
feed_dict = batch_data.copy()
feed_dict['img_data'] = img
del feed_dict['img_ori']
del feed_dict['info']
feed_dict = async_copy_to(feed_dict, args.gpu_id)

# forward pass
pred_tmp = segmentation_module(feed_dict, segSize=segSize)
pred = pred + pred_tmp.cpu() / len(args.imgSize)

_, preds = torch.max(pred, dim=1)
preds = as_numpy(preds.squeeze(0))

# visualization
visualize_result(
(batch_data['img_ori'], batch_data['info']),
preds, args)

print('[{}] iter {}'
.format(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), i))


def main(args):
torch.cuda.set_device(args.gpu_id)

# Network Builders
builder = ModelBuilder()
net_encoder = builder.build_encoder(
arch=args.arch_encoder,
fc_dim=args.fc_dim,
weights=args.weights_encoder)
net_decoder = builder.build_decoder(
arch=args.arch_decoder,
fc_dim=args.fc_dim,
num_class=args.num_class,
weights=args.weights_decoder,
use_softmax=True)

crit = nn.NLLLoss(ignore_index=-1)

segmentation_module = SegmentationModule(net_encoder, net_decoder, crit)

# Dataset and Loader
list_test = [{'fpath_img': args.test_img}]
dataset_val = TestDataset(
list_test, args, max_sample=args.num_val)
loader_val = torchdata.DataLoader(
dataset_val,
batch_size=args.batch_size,
shuffle=False,
collate_fn=user_scattered_collate,
num_workers=5,
drop_last=True)

segmentation_module.cuda()

# Main loop
test(segmentation_module, loader_val, args)

print('Inference done!')


if __name__ == '__main__':
assert LooseVersion(torch.__version__) >= LooseVersion('0.4.0'), \
'PyTorch>=0.4.0 is required'

parser = argparse.ArgumentParser()
# Path related arguments
parser.add_argument('--test_img', required=True)
parser.add_argument('--model_path', required=True,
help='folder to model path')
parser.add_argument('--suffix', default='_epoch_20.pth',
help="which snapshot to load")

# Model related arguments
parser.add_argument('--arch_encoder', default='resnet50_dilated8',
help="architecture of net_encoder")
parser.add_argument('--arch_decoder', default='ppm_bilinear_deepsup',
help="architecture of net_decoder")
parser.add_argument('--fc_dim', default=2048, type=int,
help='number of features between encoder and decoder')

# Data related arguments
parser.add_argument('--num_val', default=-1, type=int,
help='number of images to evalutate')
parser.add_argument('--num_class', default=150, type=int,
help='number of classes')
parser.add_argument('--batch_size', default=1, type=int,
help='batchsize. current only supports 1')
parser.add_argument('--imgSize', default=[300, 400, 500, 600],
nargs='+', type=int,
help='list of input image sizes.'
'for multiscale testing, e.g. 300 400 500')
parser.add_argument('--imgMaxSize', default=1000, type=int,
help='maximum input image size of long edge')
parser.add_argument('--padding_constant', default=8, type=int,
help='maxmimum downsampling rate of the network')
parser.add_argument('--segm_downsampling_rate', default=8, type=int,
help='downsampling rate of the segmentation label')

# Misc arguments
parser.add_argument('--result', default='.',
help='folder to output visualization results')
parser.add_argument('--gpu_id', default=0, type=int,
help='gpu_id for evaluation')

args = parser.parse_args()
print(args)

# absolute paths of model weights
args.weights_encoder = os.path.join(args.model_path,
'encoder' + args.suffix)
args.weights_decoder = os.path.join(args.model_path,
'decoder' + args.suffix)

assert os.path.exists(args.weights_encoder) and \
os.path.exists(args.weights_encoder), 'checkpoint does not exitst!'

if not os.path.isdir(args.result):
os.makedirs(args.result)

main(args)
qq_41615583 2018-06-06
  • 打赏
  • 举报
回复
您好请问您是怎样解决cv2imwrite出错的问题的,我的也这样,这是我的代码
test.py

# System libs
import os
import datetime
import argparse
from distutils.version import LooseVersion
# Numerical libs
import numpy as np
import torch
import torch.nn as nn
from scipy.io import loadmat
# Our libs
from dataset import TestDataset
from models import ModelBuilder, SegmentationModule
from utils import colorEncode
from lib.nn import user_scattered_collate, async_copy_to
from lib.utils import as_numpy, mark_volatile
import lib.utils.data as torchdata
import cv2


def visualize_result(data, preds, args):
colors = loadmat('data/color150.mat')['colors']
(img, info) = data

# prediction
pred_color = colorEncode(preds, colors)

# aggregate images and save
im_vis = np.concatenate((img, pred_color),
axis=1).astype(np.uint8)

img_name = info.split('/')[-1]
cv2.imwrite(os.path.join(args.result,
img_name.replace('.jpg', '.png')), im_vis)


def test(segmentation_module, loader, args):
segmentation_module.eval()

for i, batch_data in enumerate(loader):
# process data
batch_data = batch_data[0]
segSize = (batch_data['img_ori'].shape[0],
batch_data['img_ori'].shape[1])

img_resized_list = batch_data['img_data']

with torch.no_grad():
pred = torch.zeros(1, args.num_class, segSize[0], segSize[1])

for img in img_resized_list:
feed_dict = batch_data.copy()
feed_dict['img_data'] = img
del feed_dict['img_ori']
del feed_dict['info']
feed_dict = async_copy_to(feed_dict, args.gpu_id)

# forward pass
pred_tmp = segmentation_module(feed_dict, segSize=segSize)
pred = pred + pred_tmp.cpu() / len(args.imgSize)

_, preds = torch.max(pred, dim=1)
preds = as_numpy(preds.squeeze(0))

# visualization
visualize_result(
(batch_data['img_ori'], batch_data['info']),
preds, args)

print('[{}] iter {}'
.format(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), i))


def main(args):
torch.cuda.set_device(args.gpu_id)

# Network Builders
builder = ModelBuilder()
net_encoder = builder.build_encoder(
arch=args.arch_encoder,
fc_dim=args.fc_dim,
weights=args.weights_encoder)
net_decoder = builder.build_decoder(
arch=args.arch_decoder,
fc_dim=args.fc_dim,
num_class=args.num_class,
weights=args.weights_decoder,
use_softmax=True)

crit = nn.NLLLoss(ignore_index=-1)

segmentation_module = SegmentationModule(net_encoder, net_decoder, crit)

# Dataset and Loader
list_test = [{'fpath_img': args.test_img}]
dataset_val = TestDataset(
list_test, args, max_sample=args.num_val)
loader_val = torchdata.DataLoader(
dataset_val,
batch_size=args.batch_size,
shuffle=False,
collate_fn=user_scattered_collate,
num_workers=5,
drop_last=True)

segmentation_module.cuda()

# Main loop
test(segmentation_module, loader_val, args)

print('Inference done!')


if __name__ == '__main__':
assert LooseVersion(torch.__version__) >= LooseVersion('0.4.0'), \
'PyTorch>=0.4.0 is required'

parser = argparse.ArgumentParser()
# Path related arguments
parser.add_argument('--test_img', required=True)
parser.add_argument('--model_path', required=True,
help='folder to model path')
parser.add_argument('--suffix', default='_epoch_20.pth',
help="which snapshot to load")

# Model related arguments
parser.add_argument('--arch_encoder', default='resnet50_dilated8',
help="architecture of net_encoder")
parser.add_argument('--arch_decoder', default='ppm_bilinear_deepsup',
help="architecture of net_decoder")
parser.add_argument('--fc_dim', default=2048, type=int,
help='number of features between encoder and decoder')

# Data related arguments
parser.add_argument('--num_val', default=-1, type=int,
help='number of images to evalutate')
parser.add_argument('--num_class', default=150, type=int,
help='number of classes')
parser.add_argument('--batch_size', default=1, type=int,
help='batchsize. current only supports 1')
parser.add_argument('--imgSize', default=[300, 400, 500, 600],
nargs='+', type=int,
help='list of input image sizes.'
'for multiscale testing, e.g. 300 400 500')
parser.add_argument('--imgMaxSize', default=1000, type=int,
help='maximum input image size of long edge')
parser.add_argument('--padding_constant', default=8, type=int,
help='maxmimum downsampling rate of the network')
parser.add_argument('--segm_downsampling_rate', default=8, type=int,
help='downsampling rate of the segmentation label')

# Misc arguments
parser.add_argument('--result', default='.',
help='folder to output visualization results')
parser.add_argument('--gpu_id', default=0, type=int,
help='gpu_id for evaluation')

args = parser.parse_args()
print(args)

# absolute paths of model weights
args.weights_encoder = os.path.join(args.model_path,
'encoder' + args.suffix)
args.weights_decoder = os.path.join(args.model_path,
'decoder' + args.suffix)

assert os.path.exists(args.weights_encoder) and \
os.path.exists(args.weights_encoder), 'checkpoint does not exitst!'

if not os.path.isdir(args.result):
os.makedirs(args.result)

main(args)
LYY0394 2017-05-26
  • 打赏
  • 举报
回复
请问是怎么解决的,能否共享?我也遇到了类似问题,但是一直没找到解决方案,多谢!
Ginter_ 2016-09-13
  • 打赏
  • 举报
回复
既然解决了,解决方法都不想透露出来,那你刚开始问的初衷是什么
tiaowei9500 2016-07-30
  • 打赏
  • 举报
回复
是呀 所以才来问一下 因为书上跟网上的教程都用这个函数(语句)来保存摄像头的图片。。。。。。 为什么不能用了呢?
shaode01 2016-07-30
  • 打赏
  • 举报
回复
报错很清楚,cv没有那个函数
tiaowei9500 2016-07-30
  • 打赏
  • 举报
回复
已解决 !!!!!!!

37,743

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧