python 调用dll如何返回多个值 5C

import scipy.io as scio
import os
import ctypes
import datetime
import numpy as np

#读取dll文件
#这里的地址目录是HessianFilter.dll所在的文件夹
start = datetime.datetime.now()
cur_path = os.path.dirname(r'C:\Users\Administrator\Desktop\code_and_data\code\HessianFilter\')
dll_path = os.path.join(cur_path,'HessianFilter.dll')
print dll_path
dll = ctypes.windll.LoadLibrary(dll_path)

#读取mat文件,Mat文件所在的文件夹中读取
matPath = r'C:\Users\Administrator\Desktop\code_and_data\data\Nodule19664.mat'
imgData = scio.loadmat(matPath)

#从mat文件中我们取到了整个三维数组
imgDataArray = imgData['imagetest1']

#得到数组文件的参数:宽,高,层数
widthSrc,heightSrc,sliceNumSrc = imgDataArray.shape

#声明一个三维的c_float类型的数组,用于存放mat数据,并将数据转化为c_float
imgDataArray_p = (((ctypes.c_float*sliceNumSrc)*heightSrc)*widthSrc)()

for i in range(widthSrc):
for j in range(heightSrc):
for k in range(sliceNumSrc):
imgDataArray_p[i][j][k] = ctypes.c_float(imgDataArray[i][j][k])

imgDataP = ctypes.POINTER(ctypes.c_float)(imgDataArray_p)
print '---------->'
#需要再声明两个返回值
HessianDot = (ctypes.c_float*(widthSrc*heightSrc*sliceNumSrc))()
HessianLine = (ctypes.c_float*(widthSrc*heightSrc*sliceNumSrc))()

HessianDot_p = ctypes.POINTER(ctypes.c_float)(HessianDot)
HessianLine_p = ctypes.POINTER(ctypes.c_float)(HessianLine)

#定义一个常数
sigma = ctypes.c_float(8)

#定义一个三维数组
imgSize = [widthSrc,heightSrc,sliceNumSrc]
imageSize = (ctypes.c_float*len(imgSize))(*imgSize)

#定义一个指向三维数组的指针
imageSizeP = ctypes.POINTER(ctypes.c_float)(imageSize)

#这个就是调用dll中的函数了
dll.RunHessianMultiThread(ctypes.byref(imgDataArray_p),sigma,ctypes.byref(imageSizeP),ctypes.byref(HessianDot_p),ctypes.byref(HessianLine_p),4)
print '--调用后-点数据--'
print HessianDot_p
print HessianDot_p[0:24]
#print HessianDot_p.contents
print '--调用后-线数据--'
print HessianLine_p
print HessianLine_p[0:24]
#print HessianLine_p.contents
print '<---------Over------------->\n\n'
print datetime.datetime.now()-start

1个回答

一般来说函数要返回多个值,要么参数中使用指针,要么返回结构体或者数组

wwwtttnnnyyy
希望可以聪明点 RunHessianMultiThread函数中传入了HessianDot_p和HessianLine_p两个指针,就是不知道传入的对不对?这个怎么整呢?
接近 3 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
python 调用C++ dll (该dll 依赖其他dll)

问题描述: C++中有两个类 bclass 和 nclass,其中nclass 里面的一个private变量就是bclass。 这两个类目前都被写成了动态库 libbclass.so 和 libnclass.so。 当我在Python中利用ctypes模块希望调用libnclass.so的时候,程序报错 OSError: libbclass.so: cannot open shared object file: No such file or directory 我的问题: 1、如何调用libnclass.so 2、如何在python中创建一个nclass类的实例,并调用该实例的方法add

python调用DLL,c++,用vs编译的

我的程序是让一个csv文件生成多个csv文件!所以输入的参数有输入文件名,输出文件名,日期分割点等。c语言程序没有问题的,运行过了!dll也是正常生成的。但是用python运行后没有任何反应,没错误提示也没有生成需要的csv文件!!希望大神帮忙看看吧!!!分别是csv.c csv.h python的代码![图片说明](https://img-ask.csdn.net/upload/201706/12/1497254637_942334.png)![图片说明](https://img-ask.csdn.net/upload/201706/12/1497254643_96080.png)![图片说明](https://img-ask.csdn.net/upload/201706/12/1497254966_579917.png)

如何把Python的.py文件转为DLL文件用于调用呢?

我是一枚Python新手,现在手上有一个python的Test.py文件,一个利用cython生成C的setup.py文件,通过命令行生成Test.c文件。 然后应该就可以使用.def文件生成dll文件了,但运行后,会有关于def文件中我方法名的报错:外部无法解析的外部符号。但方法名和我原py文件的方法名是一致的,为什么会报错呢? 或者有其他转dll的好办法吗?详细一些的,谢谢了。

用ctypes向dll传入的数组,返回python后,其中的数据有时正确有时错误,怎么办?

运行环境: win10 + anaconda5.3 + jupyter python文件 ``` import numpy as np import pandas as pd mylib = ctypes.cdll.LoadLibrary('mydll.dll') C_fun = mylib.func_name C_fun.restypes = None C_fun.argtypes = pass_args_Struct, c_double*10 # pass_args_Struct 是继承ctypes.Structure定义的结构体,代码略 def generate_Struct(data, 其他参数略): # 生成 pass_args_Struct,代码略 # data是个DataFrame,用于接收下面myClass的data属性 class myClass(): # myclass有个data属性,data是一个DataFrame # 其他代码略 def func1(self, x): # 删除self.data的一列,再根据x参数重新添加这一列,代码略 struct_x = generate_Struct(self.data, 其他参数略) myArr = (c_double*10)() C_fun(struct_x, myArr) npArr = np.ctypeslib.as_array(myArr,(10,)) return pd.Series(npArr, _column_names) # _column_names 定义略 def func2(self): # 生成df,df是个只有一列值的DataFrame,代码略 return df.apply(lamba x: self.func1(x[0]), axis=1, result_type='expand')) # 其他代码略 ``` mydll.dll中的代码 ``` #define API extern "C" __declspec(dllexport) typedef pass_args_Struct { // 对应于python中pass_args_Struct,代码略 } API void func_name(pass_args_Struct* x, double arr[]) { // 对arr进行一些操作,代码略 } ``` 在jupyter中: 导入前述Python文件并生成 myObject=myClass() 之后, 执行ret1 = myObject.func1()没什么问题, 但是ret2 = myObject.func2()的结果则有时正确有时错误,错误的时候,ret2中会出现一些NaN值和错误的值。 之前把generate_Struct()定义成myclass的一个方法,连ret1也会出错; 之前的func1(self, x)中采用: ``` func1(self, x): # 其他代码略 myArr = np.ctypeslib.as_array(myArr,(10,)) # 左边不用新名而直接用myArr return pd.Series(myArr, _column_names) ``` 则ret1会频繁出错,基本上是对一次就错一次。 程序一直能运行,只是结果有时不正确。 请教各位大牛,正确的写法是什么样子的? ==================================================== =====2018年11月30日更新==================================== 我可能发现问题了: Python文件TestX.py(放在PYTHONPATH下): ``` import numpy as np from ctypes import Structure, c_double, c_int, POINTER class struct_args(Structure): _fields_ = [('data',POINTER(c_double*2)), ('rows',c_int)] class test(): def __init__(self): self.data = None def get_args_2C(self): arr = np.ascontiguousarray(self.data[['foo','bar']].values, dtype=np.float) rows = c_int(arr.shape[0]) return struct_args(arr.ctypes.data_as(POINTER(c_double*2)), rows) ``` 在jupyter中: ``` import TestX import pandas as pd import numpy as np mydata = pd.DataFrame(np.arange(1600).reshape(800,2),columns=['foo','bar']) # 行数不要太小 mytest = TestX.test() mytest.data = mydata args = mytest.get_args_2C() np.ctypeslib.as_array(args.data,(800,)) ``` 输出的值经常是错误的。 ==================================================== =====2018年12月3日更新==================================== 不知道为什么,但总算是不出错了: python文件: ``` from ctypes import Structure,POINTER,c_double def Struct_A(ctypes.Structure): _fields_ = [(), # 其他成员略 ('my_arr',POINTER(c_double)] # 这个地方用c_double*10后面也会出错 class myClass(): def makeStructA(self, 其他参数): arr = (c_double*10)() SA = Struct_A(……,arr) # 其他成员略 return SA def myMethod(self, 其他参数): SA = self.makeStructA(其他参数) # myCfun是dll中的函数,功能是利用SA中数据进行一些计算,然后把结果写入SA.my_arr,具体代码略 myCfun(SA) ret = pd.Series(np.ctypeslib.as_array(SA.my_arr,(10,)), _columns_name) ret['odd'] = 1 # 这里随便新加点什么就不会出错了 return ret ``` 以上代码如果没有ret['odd']=1那一行,则myObject.myMethod()返回的Series中都是错误的值(看着像是内存未初始化,比如-2.24934335e308之类),而随便给ret添加点什么内容,返回值就是正确的了。 但是在以下计算中仍然会出错,只是出错的频率变小了,而且多运行几次就会正确: ``` class myClass(): # 接上文 def myOptimize(self, arg_name, arg_range): ret = pd.DataFrame({arg_name:arg_range}) _optimize = lambda arg: self.myMethod(**{arg_name:arg[arg_name]}) return ret.join(ret.apply(_optimize, axis=1, result_type='expand')) ``` ===================================== =====2018年12月7日更新==================================== 又出错了!!!12月3日写的: ``` ret['odd'] = 1 # 这里随便新加点什么就不会出错了 ``` 那个函数确实不出错了,但是别的函数用同样的写法(先生成c_double*shape再传入dll在C中写入值)得到的ret无论添加行还是添加列,多运行几次总会出错(内存被清理)。 换一种写法: ``` 略 arr=np.zeros(shape) 略 # 然后传入arr.ctypes.data_as(POINTER(c_double*10)) ``` 目前暂时不出错了。 =====2018年12月13日更新==================================== 前面的写法有问题:用函数生成结构体(比如makeStructA)再传递给dll就会出错,直接将makeStuctA的代码放到myMethod中就不会出错。 另外,传递结构体时用byref就不会出错了,在dll中用malloc给结构体的成员赋值都不会出错。

Python的类怎么调用其他类的方法?

事情是这样的。我用wxpython写了一个窗体程序,定义了一个“MyButton”类(继承了Button)和一个“TextBox”类(继承了TextCtrl),会产生一个按钮和一个文本框。点击按钮就能清空文本框里的内容。将这个特性定义成了Button的方法,可是怎么去调用TextBox里的Clear()方法?这个时候还没有定义对象。

C#如何动态调用VB编译的dll里的函数

有一个VB的工程项目,里面有很多类,每个类里都有相同的函数; 比如 a工程;类模块里有 b类,c类;而b类和c类都有相同的函数d; 我怎么在C#里动态调用b类的d函数呢? 因为是动态调用,所以不能是直接引用dll,再“对象名.函数名”; DLLImport和反射都尝试过,关键是我要定位到某个类的那个函数,就不知道怎么弄,麻烦大神帮帮忙

Python ctypes 中回调函数设置

我在python中想调用dll库的函数,但是这个dll库的函数参数需要设置一个回调函数指针,如下 void setCallBack(void(*)(Data &a)) Data is C struct, declare as below typedef struct { int index, .... }Data 我在python中调用代码如下: mydll = cdll.LoadLibrary("XXX.dll") callback_type = CFUNCTYPE(None, POINTER(Data)) callback = callback_type(Data) mydll.setCallBack(callback) def dataResponse(data): print data.index class Data(ctypes.Structure): _fields_ = [("index", c_int)] 调用时发生"WindowsError: [Error -1073741795] Windows Error 0xC000001D"错误, 请大家帮忙看一下如何设置回调函数,感觉如何参数类型是C++引用的话,POINTER好像是不对的。

python调用com接口问题

请教下各位,用python实现VISSIM(交通仿真软件)的调用。能够打开软件,载入文件。但实现不了对API的调用,关联不到typelibaray(写代码时也没自动补全)。 代码如下:# -*- coding: utf-8 -*- import win32com.client as com Vissim = com.Dispatch("Vissim.Vissim") Filename = r'E:\study\1.inp' Vissim.LoadNet(Filename) Link_number = 1 Name_of_Link = Vissim.Net.Links.ItemByKey(Link_number).AttValue('Name') print 'Name of Link(',Link_number,'):',Name_of_Link #获得道路名称 错误提示: Traceback (most recent call last): File "<string>", line 254, in run_nodebug File "C:\Users\Administrator\Desktop\develop\LOAD3.py", line 19, in <module> Name_of_Link = Vissim.Net.Links.ItemByKey(Link_number).AttValue('Name') File "D:\Python\lib\site-packages\win32com\client\dynamic.py", line 527, in __getattr__ raise AttributeError("%s.%s" % (self._username_, attr)) AttributeError: <unknown>.ItemByKey 这是什么原因呢,请大手子解答下~金币不多,请见谅 也试过用regsvr32 和 regam 去注册dll文件(不清楚是哪个就都试了一遍) ![图片说明](https://img-ask.csdn.net/upload/201705/15/1494819662_358196.png)

求助关于vc调用autohotkey.dll

http://blog.csdn.net/liuyukuan/article/details/5949727 利用这个博客中的方法能够调用脚本了,可是很多函数不知道如何用 比如:(用mfc添加类型库生成的头文件) VARIANT ahkgetvar(VARIANT& name, VARIANT& getVar) { VARIANT result; static BYTE parms[] = VTS_VARIANT VTS_VARIANT; InvokeHelper(0x6, DISPATCH_METHOD, VT_VARIANT, (void*)&result, parms, &name, &getVar); return result; } 帮助文档是这么写的: "ahkgetvar is used to get a value from a variable in script. Similar to GetVar. 用于在脚本变量获取值" VarName Name of variable to get value from. getPointer Get value or pointer. Use 1 to get pointer of variable, for example to use with Alias, else 0 to get the value. 然后我在头文件中声明如下: typedef int(*ahkgetvar)(wchar_t *, wchar_t *); 在实现部分添加: ahkgetvar ahkgetvar_ = (ahkgetvar)GetProcAddress(hinstLib, "ahkgetvar"); int s = ahkgetvar_(L"a", L"0");//在脚本中定义了一个变量a=0 cout << s << endl; 然后得到的每次的值都不同 主要是没搞懂VARIANT变量怎么用

Python3.7+Pyside2 运行exe文件提示“ImportError: DLL load failed: 找不到指定的程序。

# Python3.7+Pyside2 运行exe文件提示“ImportError: DLL load failed: 找不到指定的程序 1.问题描述 a.python 3.7 + pyside2 (只用pyside2,没有使用PyQt5) b.使用pyinstaller -F xxx.py 打包,生成xxx.exe c.使用cmd运行exe文件 2.报错 Traceback (most recent call last): File "PyInstaller\loader\rthooks\pyi_rth_qt5plugins.py", line 47, in <module> ModuleNotFoundError: No module named 'PyQt5' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "PyInstaller\loader\rthooks\pyi_rth_qt5plugins.py", line 49, in <module> ImportError: DLL load failed: 找不到指定的程序。 [16072] Failed to execute script pyi_rth_qt5plugins 不知道为啥提示No module named 'PyQt5',在安装的lib中也只有pyside2; 多谢大神指点。 20190730,更新: 经过多次尝试和修改,发现lib库的安装的问题。代码中没有调用QT5的,在lib安装的时候,如果是使用pycharm setting中安装,安装的路径是在项目的文件夹,如果使用python的终端命令pip进行安装,安装在python的lib目录下,两个路径有时候不能完全的调用。 后来重新都是统一使用python 终端 pip命令安装,问题解决。

python3使用ctypes有些c类型没有怎么办?

被实习作业折磨到摸不着头脑 菜狗一只,平常总是靠度娘解决问题,但这次真的搜不到了(╥╯^╰╥) 实在不想用C++......而且已经丢了很久了...... 学校实习任务开发指纹仪的相关软件,调用dll函数。 问题1: dll函数:HANDLE_stdcall sensorOpen(int index) 这个类型是句柄HANDLE,其返回值需要用到,但是Python没有直接HANDLE,我用int接收暂没出现问题,怕之后会遇到先问一个。 问题2: dll函数:int_stdcall sensorCapture(HANDLE handle,unsigned char* imageBuffer, int imageBufferSize)//获取图像 handle就是上面那个,unsigned char* 文档解释是接收的图像即是输入的参数也会输出,后续指纹算法需要,ctypes也没有,怎么实现? 我目前使用imageBuffer = create_string_buffer(所需空间大小),但是没有采集到图像(我检验了该函数返回值,为0,即无图像) 我也试过了create_unicode_buffer,结果也一样。到底是使用方法问题还是其他导致我真的没采集到图像 问题3:(虽然前面的还没解决但先问下)(准确的说目前卡在这里) dll函数:HANDLE stdcall BIOKEY_INIT(int License, WORD *isize, BYTE*Params, BYTE *Buffer, intImageFlag) 问题出在isize:文档描述:[in] 传入一个无符号双字节长度为22 的数组,且 isize[0]和isize[20]为传入图像宽度,isize[1]和 isize[21]为传入图像高度 这isize怎么提前定义? 我尝试使用isize = bytearray()处理,但是毕竟是双字节,光是宽度就有300多,但byte要在0-255之间,而且还不确定都是数字(我试过定义为整型数组,报错don't konw how to convert parameter 2)。作为指纹图像,虽然有函数可以修改采集图像的大小,但是太小了的话数据的完整性和可使用性就大打折扣。所以这个双字节咋整啊 问题4: 有些函数传入参数为int*,咋整......我先去看看ctypes的文档,但是我记得上次看的时候好像没有针对这种指针的...直接使用c_char_p吗?(目前没法验证这个方法是否可行,因为前面就走不通。。。) 总之目前就这些了,实习作业周三开始检查希望会的大佬帮帮我!谢谢啦! 我先滚去看文档了。。。

python的ctypes加载遇到相互依赖的库如何处理?

现在又两个库函数a.so和b.so,现在想加载a库实现a库里的ar方法,加载a库的时候报错提示OSError: /usr/lib/a.so: undefined symbol:bf,经过核实bf在b库里于是加载b库,发现b库也报错OSError: /usr/lib/b.so: undefined symbol:af,进经过了解两个库相互依赖,导致ctyps两个库都无法加载,从而不能实现a库方法的调用。想问下大家: 1.这类问题如何处理? 2.有没有指定加载库里的函数的方法

运行python批处理文件,报了一个缺少属性“key”错误,找到源码但是看不懂,求大佬们解答

在使用自己的数据集做训练时,用到一个retrain.py的文件,之后通过批处理文件运行 以下是批处理文件代码: ``` python D:\python\Anaconda\envs\tensorflow\tensorflow-master\tensorflow\examples\image_retraining\retrain.py ^ --bottleneck_dir bottleneck ^ --how_many_training_steps 200 ^ --model_dir D:\python\Anaconda\envs\tensorflow\inception_model ^ --output_graph output_graph.pb ^ --output_labels output_labels.txt ^ --image_dir data/train/ pause ``` 调用时,报了 File "D:\python\Anaconda\envs\tensorflow\tensorflow-master\tensorflow\examples\image_retraining\retrain.py", line 1313, in <module> tf.app.run(main=main, argv=[sys.argv[0]] + unparsed) File "D:\python\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\platform\app.py", line 125, in run _sys.exit(main(argv)) File "D:\python\Anaconda\envs\tensorflow\tensorflow-master\tensorflow\examples\image_retraining\retrain.py", line 982, in main class_count = len(image_lists.keys()) AttributeError: 'NoneType' object has no attribute 'keys' 错误最后是说982行缺少keys属性,但不知如何修改 retrain代码太长,只能把链接发上来

python flask包使用。。。。。

![图片说明](https://img-ask.csdn.net/upload/202002/06/1580974180_632939.jpg)![图片说明](https://img-ask.csdn.net/upload/202002/06/1580974198_207304.png)![图片说明](https://img-ask.csdn.net/upload/202002/06/1580974206_672162.png) 按书中,在jupyter中写了段使用flask包的代码,放在cmd中运行不出,请问这个问题如何解决

YOLO在python中调用设置darknet.set_gpu(1)无效

我的操作系统是macos,显卡为GT750M,已经成功安装了cuda,在终端调用yolo官网的示例代码可以实现gpu运算,但在python中按照作者封装好的darknet.py调用yolo时设置darknet.set_gpu(1)却无法使用gpu运算,仍是cpu运算。 我在/src/cuda.c中把cuda_set_device函数的gpu_index直接设置为1,仍无法使用gpu运算,我对c++了解的不是很多,希望大神可以帮我解决这个问题。

C# 请教这个设置多显示器复制扩展的类怎么调用?麻烦各位了!

``` #region Copyright (C) 2005-2011 Team MediaPortal // Copyright (C) 2005-2011 Team MediaPortal // http://www.team-mediaportal.com // // MediaPortal is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // MediaPortal is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with MediaPortal. If not, see <http://www.gnu.org/licenses/>. #endregion #region using using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; #endregion namespace ImageViewer { public class W7RefreshRateHelper { #region consts private const uint SIZE_OF_DISPLAYCONFIG_PATH_INFO = 72; private const uint SIZE_OF_DISPLAYCONFIG_MODE_INFO = 64; private const uint QDC_ALL_PATHS = 1; private const uint DISPLAYCONFIG_MODE_INFO_TYPE_TARGET = 2; private const uint DISPLAYCONFIG_SCANLINE_ORDERING_PROGRESSIVE = 1; public const uint SDC_TOPOLOGY_INTERNAL = 0x00000001; public const uint SDC_TOPOLOGY_CLONE = 0x00000002; public const uint SDC_TOPOLOGY_EXTEND = 0x00000004; public const uint SDC_TOPOLOGY_EXTERNAL = 0x00000008; public const uint SDC_TOPOLOGY_SUPPLIED = 0x00000010; public const uint SDC_USE_DATABASE_CURRENT = (SDC_TOPOLOGY_INTERNAL | SDC_TOPOLOGY_CLONE | SDC_TOPOLOGY_EXTEND | SDC_TOPOLOGY_EXTERNAL); private const uint SDC_USE_SUPPLIED_DISPLAY_CONFIG = 0x00000020; private const uint SDC_VALIDATE = 0x00000040; private const uint SDC_APPLY = 0x00000080; private const uint SDC_ALLOW_CHANGES = 0x00000400; private const uint SDC_NO_OPTIMIZATION = 0x00000100; private const uint SDC_SAVE_TO_DATABASE = 0x00000200; private const uint SDC_PATH_PERSIST_IF_REQUIRED = 0x00000800; private const uint SDC_FORCE_MODE_ENUMERATION = 0x00001000; private const uint SDC_ALLOW_PATH_ORDER_CHANGES = 0x00002000; #endregion #region DLL imports [DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern long GetDisplayConfigBufferSizes([In] uint flags, [Out] out uint numPathArrayElements, [Out] out uint numModeArrayElements); [DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern long QueryDisplayConfig([In] uint flags, ref uint numPathArrayElements, IntPtr pathArray, ref uint numModeArrayElements, IntPtr modeArray, IntPtr currentTopologyId); [DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern long SetDisplayConfig(uint numPathArrayElements, IntPtr pathArray, uint numModeArrayElements, IntPtr modeArray, uint flags); #endregion #region private members private static int GetModeInfoOffsetForDisplayId(uint displayIndex, IntPtr pModeArray, uint uNumModeArrayElements) { int offset; int modeInfoType; // there are always two mode infos per display (target and source) offset = (int)(displayIndex * SIZE_OF_DISPLAYCONFIG_MODE_INFO * 2); // out of bounds sanity check if (offset + SIZE_OF_DISPLAYCONFIG_MODE_INFO >= uNumModeArrayElements * SIZE_OF_DISPLAYCONFIG_MODE_INFO) { return -1; } // check which one of the two mode infos for the display is the target modeInfoType = Marshal.ReadInt32(pModeArray, offset); if (modeInfoType == DISPLAYCONFIG_MODE_INFO_TYPE_TARGET) { return offset; } else { offset += (int)SIZE_OF_DISPLAYCONFIG_MODE_INFO; } modeInfoType = Marshal.ReadInt32(pModeArray, offset); if (modeInfoType == DISPLAYCONFIG_MODE_INFO_TYPE_TARGET) { return offset; } // no target mode info found, this should never happen else { return -1; } } #endregion #region public members public static double GetRefreshRate(uint displayIndex) { uint uNumPathArrayElements = 0; uint uNumModeArrayElements = 0; IntPtr pPathArray = IntPtr.Zero; IntPtr pModeArray = IntPtr.Zero; IntPtr pCurrentTopologyId = IntPtr.Zero; long result; UInt32 numerator; UInt32 denominator; double refreshRate; // get size of buffers for QueryDisplayConfig result = GetDisplayConfigBufferSizes(QDC_ALL_PATHS, out uNumPathArrayElements, out uNumModeArrayElements); if (result != 0) { // Log.Error("W7RefreshRateHelper.GetRefreshRate: GetDisplayConfigBufferSizes(...) returned {0}", result); return 0; } // allocate memory or QueryDisplayConfig buffers pPathArray = Marshal.AllocHGlobal((Int32)(uNumPathArrayElements * SIZE_OF_DISPLAYCONFIG_PATH_INFO)); pModeArray = Marshal.AllocHGlobal((Int32)(uNumModeArrayElements * SIZE_OF_DISPLAYCONFIG_MODE_INFO)); // get display configuration result = QueryDisplayConfig(QDC_ALL_PATHS, ref uNumPathArrayElements, pPathArray, ref uNumModeArrayElements, pModeArray, pCurrentTopologyId); // if failed log error message and free memory if (result != 0) { // Log.Error("W7RefreshRateHelper.GetRefreshRate: QueryDisplayConfig(...) returned {0}", result); Marshal.FreeHGlobal(pPathArray); Marshal.FreeHGlobal(pModeArray); return 0; } // get offset for a display's target mode info int offset = GetModeInfoOffsetForDisplayId(displayIndex, pModeArray, uNumModeArrayElements); // if failed log error message and free memory if (offset == -1) { //Log.Error("W7RefreshRateHelper.GetRefreshRate: Couldn't find a target mode info for display {0}", displayIndex); Marshal.FreeHGlobal(pPathArray); Marshal.FreeHGlobal(pModeArray); return 0; } // get refresh rate numerator = (UInt32)Marshal.ReadInt32(pModeArray, offset + 32); denominator = (UInt32)Marshal.ReadInt32(pModeArray, offset + 36); refreshRate = (double)numerator / (double)denominator; //Log.Debug("W7RefreshRateHelper.GetRefreshRate: QueryDisplayConfig returned {0}/{1}", numerator, denominator); // free memory and return refresh rate Marshal.FreeHGlobal(pPathArray); Marshal.FreeHGlobal(pModeArray); return refreshRate; } public static bool SetRefreshRate(uint displayIndex, double refreshRate) { uint uNumPathArrayElements = 0; uint uNumModeArrayElements = 0; IntPtr pPathArray = IntPtr.Zero; IntPtr pModeArray = IntPtr.Zero; IntPtr pCurrentTopologyId = IntPtr.Zero; long result; UInt32 numerator; UInt32 denominator; UInt32 scanLineOrdering; UInt32 flags; // get size of buffers for QueryDisplayConfig result = GetDisplayConfigBufferSizes(QDC_ALL_PATHS, out uNumPathArrayElements, out uNumModeArrayElements); if (result != 0) { // Log.Error("W7RefreshRateHelper.GetRefreshRate: GetDisplayConfigBufferSizes(...) returned {0}", result); return false; } // allocate memory or QueryDisplayConfig buffers pPathArray = Marshal.AllocHGlobal((Int32)(uNumPathArrayElements * SIZE_OF_DISPLAYCONFIG_PATH_INFO)); pModeArray = Marshal.AllocHGlobal((Int32)(uNumModeArrayElements * SIZE_OF_DISPLAYCONFIG_MODE_INFO)); // get display configuration result = QueryDisplayConfig(QDC_ALL_PATHS, ref uNumPathArrayElements, pPathArray, ref uNumModeArrayElements, pModeArray, pCurrentTopologyId); // if failed log error message and free memory if (result != 0) { // Log.Error("W7RefreshRateHelper.GetRefreshRate: QueryDisplayConfig(...) returned {0}", result); Marshal.FreeHGlobal(pPathArray); Marshal.FreeHGlobal(pModeArray); return false; } // get offset for a display's target mode info int offset = GetModeInfoOffsetForDisplayId(displayIndex, pModeArray, uNumModeArrayElements); // if failed log error message and free memory if (offset == -1) { //Log.Error("W7RefreshRateHelper.GetRefreshRate: Couldn't find a target mode info for display {0}", displayIndex); Marshal.FreeHGlobal(pPathArray); Marshal.FreeHGlobal(pModeArray); return false; } // TODO: refactor to private method // set proper numerator and denominator for refresh rate UInt32 newRefreshRate = (uint)(refreshRate * 1000); switch (newRefreshRate) { case 23976: numerator = 24000; denominator = 1001; scanLineOrdering = DISPLAYCONFIG_SCANLINE_ORDERING_PROGRESSIVE; break; case 24000: numerator = 24000; denominator = 1000; scanLineOrdering = DISPLAYCONFIG_SCANLINE_ORDERING_PROGRESSIVE; break; case 25000: numerator = 25000; denominator = 1000; scanLineOrdering = DISPLAYCONFIG_SCANLINE_ORDERING_PROGRESSIVE; break; case 30000: numerator = 30000; denominator = 1000; scanLineOrdering = DISPLAYCONFIG_SCANLINE_ORDERING_PROGRESSIVE; break; case 50000: numerator = 50000; denominator = 1000; scanLineOrdering = DISPLAYCONFIG_SCANLINE_ORDERING_PROGRESSIVE; break; case 59940: numerator = 60000; denominator = 1001; scanLineOrdering = DISPLAYCONFIG_SCANLINE_ORDERING_PROGRESSIVE; break; case 60000: numerator = 60000; denominator = 1000; scanLineOrdering = DISPLAYCONFIG_SCANLINE_ORDERING_PROGRESSIVE; break; default: numerator = (uint)(newRefreshRate / 1000); denominator = 1; scanLineOrdering = DISPLAYCONFIG_SCANLINE_ORDERING_PROGRESSIVE; break; } // set refresh rate parameters in display config Marshal.WriteInt32(pModeArray, offset + 32, (int)numerator); Marshal.WriteInt32(pModeArray, offset + 36, (int)denominator); Marshal.WriteInt32(pModeArray, offset + 56, (int)scanLineOrdering); // validate new refresh rate flags = SDC_VALIDATE | SDC_USE_SUPPLIED_DISPLAY_CONFIG; result = SetDisplayConfig(uNumPathArrayElements, pPathArray, uNumModeArrayElements, pModeArray, flags); // adding SDC_ALLOW_CHANGES to flags if validation failed if (result != 0) { //Log.Debug("W7RefreshRateHelper.SetDisplayConfig(...): SDC_VALIDATE of {0}/{1} failed", numerator, denominator); flags = SDC_APPLY | SDC_USE_SUPPLIED_DISPLAY_CONFIG | SDC_ALLOW_CHANGES; } else { //Log.Debug("W7RefreshRateHelper.SetDisplayConfig(...): SDC_VALIDATE of {0}/{1} succesful", numerator, denominator); flags = SDC_APPLY | SDC_USE_SUPPLIED_DISPLAY_CONFIG; } // configuring display result = SetDisplayConfig(uNumPathArrayElements, pPathArray, uNumModeArrayElements, pModeArray, flags); // if failed log error message and free memory if (result != 0) { //Log.Error("W7RefreshRateHelper.SetDisplayConfig(...): SDC_APPLY returned {0}", result); Marshal.FreeHGlobal(pPathArray); Marshal.FreeHGlobal(pModeArray); return false; } // refresh rate change successful Marshal.FreeHGlobal(pPathArray); Marshal.FreeHGlobal(pModeArray); return true; } public static bool SetScreen(uint displayModel) { return SetDisplayConfig(0, IntPtr.Zero, 0, IntPtr.Zero, SDC_APPLY | displayModel) == 0; } #endregion } } ```

pyinstaller打包后,在别的机子运行出错?

求大大帮忙 python3.64版本 [rabird.winio](https://pypi.org/project/rabird.winio/ "") ←地址 简单的官方模块示例,本机打包运行没问题, 在其他机子就报错 ![图片说明](https://img-ask.csdn.net/upload/201805/10/1525958507_215901.png) 示例代码: ``` import rabird.winio import time import atexit # KeyBoard Commands # Command port KBC_KEY_CMD = 0x64 # Data port KBC_KEY_DATA = 0x60 __winio = None def __get_winio(): global __winio if __winio is None: __winio = rabird.winio.WinIO() def __clear_winio(): global __winio __winio = None atexit.register(__clear_winio) return __winio def wait_for_buffer_empty(): ''' Wait keyboard buffer empty ''' winio = __get_winio() dwRegVal = 0x02 while (dwRegVal & 0x02): dwRegVal = winio.get_port_byte(KBC_KEY_CMD) def key_down(scancode): winio = __get_winio() wait_for_buffer_empty() winio.set_port_byte(KBC_KEY_CMD, 0xd2) wait_for_buffer_empty() winio.set_port_byte(KBC_KEY_DATA, scancode) def key_up(scancode): winio = __get_winio() wait_for_buffer_empty() winio.set_port_byte( KBC_KEY_CMD, 0xd2) wait_for_buffer_empty() winio.set_port_byte( KBC_KEY_DATA, scancode | 0x80) def key_press(scancode, press_time = 0.2): key_down( scancode ) time.sleep( press_time ) key_up( scancode ) # Press 'A' key Scancodes references : Keyboard scancodes key_press(0x1E) ```

yolo3 darknet.py问题

我用darknetAB https://github.com/AlexeyAB/darknet 编译gpu版本后生成darknet.py文件 然后我也编译了yolo_cpp_dll.sln文件 生成dll文件 然后运行darknet.py文件 不显示图片 异常退出 ![图片说明](https://img-ask.csdn.net/upload/201911/02/1572688446_628910.png) 百度了这个问题 有人说要换python3.5版本 我也尝试了 但是也是不行 不会显示图片。请问各位大佬到底怎么解决??急!!!谢谢!!! ``` #!python3 """ Python 3 wrapper for identifying objects in images Requires DLL compilation Both the GPU and no-GPU version should be compiled; the no-GPU version should be renamed "yolo_cpp_dll_nogpu.dll". On a GPU system, you can force CPU evaluation by any of: - Set global variable DARKNET_FORCE_CPU to True - Set environment variable CUDA_VISIBLE_DEVICES to -1 - Set environment variable "FORCE_CPU" to "true" To use, either run performDetect() after import, or modify the end of this file. See the docstring of performDetect() for parameters. Directly viewing or returning bounding-boxed images requires scikit-image to be installed (`pip install scikit-image`) Original *nix 2.7: https://github.com/pjreddie/darknet/blob/0f110834f4e18b30d5f101bf8f1724c34b7b83db/python/darknet.py Windows Python 2.7 version: https://github.com/AlexeyAB/darknet/blob/fc496d52bf22a0bb257300d3c79be9cd80e722cb/build/darknet/x64/darknet.py @author: Philip Kahn @date: 20180503 """ #pylint: disable=R, W0401, W0614, W0703 from ctypes import * import math import random import os def sample(probs): s = sum(probs) probs = [a/s for a in probs] r = random.uniform(0, 1) for i in range(len(probs)): r = r - probs[i] if r <= 0: return i return len(probs)-1 def c_array(ctype, values): arr = (ctype*len(values))() arr[:] = values return arr class BOX(Structure): _fields_ = [("x", c_float), ("y", c_float), ("w", c_float), ("h", c_float)] class DETECTION(Structure): _fields_ = [("bbox", BOX), ("classes", c_int), ("prob", POINTER(c_float)), ("mask", POINTER(c_float)), ("objectness", c_float), ("sort_class", c_int)] class IMAGE(Structure): _fields_ = [("w", c_int), ("h", c_int), ("c", c_int), ("data", POINTER(c_float))] class METADATA(Structure): _fields_ = [("classes", c_int), ("names", POINTER(c_char_p))] #lib = CDLL("/home/pjreddie/documents/darknet/libdarknet.so", RTLD_GLOBAL) #lib = CDLL("libdarknet.so", RTLD_GLOBAL) hasGPU = True if os.name == "nt": cwd = os.path.dirname(__file__) os.environ['PATH'] = cwd + ';' + os.environ['PATH'] winGPUdll = os.path.join(cwd, "yolo_cpp_dll.dll") winNoGPUdll = os.path.join(cwd, "yolo_cpp_dll_nogpu.dll") envKeys = list() for k, v in os.environ.items(): envKeys.append(k) try: try: tmp = os.environ["FORCE_CPU"].lower() if tmp in ["1", "true", "yes", "on"]: raise ValueError("ForceCPU") else: print("Flag value '"+tmp+"' not forcing CPU mode") except KeyError: # We never set the flag if 'CUDA_VISIBLE_DEVICES' in envKeys: if int(os.environ['CUDA_VISIBLE_DEVICES']) < 0: raise ValueError("ForceCPU") try: global DARKNET_FORCE_CPU if DARKNET_FORCE_CPU: raise ValueError("ForceCPU") except NameError: pass # print(os.environ.keys()) # print("FORCE_CPU flag undefined, proceeding with GPU") if not os.path.exists(winGPUdll): raise ValueError("NoDLL") lib = CDLL(winGPUdll, RTLD_GLOBAL) except (KeyError, ValueError): hasGPU = False if os.path.exists(winNoGPUdll): lib = CDLL(winNoGPUdll, RTLD_GLOBAL) print("Notice: CPU-only mode") else: # Try the other way, in case no_gpu was # compile but not renamed lib = CDLL(winGPUdll, RTLD_GLOBAL) print("Environment variables indicated a CPU run, but we didn't find `"+winNoGPUdll+"`. Trying a GPU run anyway.") else: lib = CDLL("./libdarknet.so", RTLD_GLOBAL) lib.network_width.argtypes = [c_void_p] lib.network_width.restype = c_int lib.network_height.argtypes = [c_void_p] lib.network_height.restype = c_int copy_image_from_bytes = lib.copy_image_from_bytes copy_image_from_bytes.argtypes = [IMAGE,c_char_p] def network_width(net): return lib.network_width(net) def network_height(net): return lib.network_height(net) predict = lib.network_predict_ptr predict.argtypes = [c_void_p, POINTER(c_float)] predict.restype = POINTER(c_float) if hasGPU: set_gpu = lib.cuda_set_device set_gpu.argtypes = [c_int] make_image = lib.make_image make_image.argtypes = [c_int, c_int, c_int] make_image.restype = IMAGE get_network_boxes = lib.get_network_boxes get_network_boxes.argtypes = [c_void_p, c_int, c_int, c_float, c_float, POINTER(c_int), c_int, POINTER(c_int), c_int] get_network_boxes.restype = POINTER(DETECTION) make_network_boxes = lib.make_network_boxes make_network_boxes.argtypes = [c_void_p] make_network_boxes.restype = POINTER(DETECTION) free_detections = lib.free_detections free_detections.argtypes = [POINTER(DETECTION), c_int] free_ptrs = lib.free_ptrs free_ptrs.argtypes = [POINTER(c_void_p), c_int] network_predict = lib.network_predict_ptr network_predict.argtypes = [c_void_p, POINTER(c_float)] reset_rnn = lib.reset_rnn reset_rnn.argtypes = [c_void_p] load_net = lib.load_network load_net.argtypes = [c_char_p, c_char_p, c_int] load_net.restype = c_void_p load_net_custom = lib.load_network_custom load_net_custom.argtypes = [c_char_p, c_char_p, c_int, c_int] load_net_custom.restype = c_void_p do_nms_obj = lib.do_nms_obj do_nms_obj.argtypes = [POINTER(DETECTION), c_int, c_int, c_float] do_nms_sort = lib.do_nms_sort do_nms_sort.argtypes = [POINTER(DETECTION), c_int, c_int, c_float] free_image = lib.free_image free_image.argtypes = [IMAGE] letterbox_image = lib.letterbox_image letterbox_image.argtypes = [IMAGE, c_int, c_int] letterbox_image.restype = IMAGE load_meta = lib.get_metadata lib.get_metadata.argtypes = [c_char_p] lib.get_metadata.restype = METADATA load_image = lib.load_image_color load_image.argtypes = [c_char_p, c_int, c_int] load_image.restype = IMAGE rgbgr_image = lib.rgbgr_image rgbgr_image.argtypes = [IMAGE] predict_image = lib.network_predict_image predict_image.argtypes = [c_void_p, IMAGE] predict_image.restype = POINTER(c_float) predict_image_letterbox = lib.network_predict_image_letterbox predict_image_letterbox.argtypes = [c_void_p, IMAGE] predict_image_letterbox.restype = POINTER(c_float) def array_to_image(arr): import numpy as np # need to return old values to avoid python freeing memory arr = arr.transpose(2,0,1) c = arr.shape[0] h = arr.shape[1] w = arr.shape[2] arr = np.ascontiguousarray(arr.flat, dtype=np.float32) / 255.0 data = arr.ctypes.data_as(POINTER(c_float)) im = IMAGE(w,h,c,data) return im, arr def classify(net, meta, im): out = predict_image(net, im) res = [] for i in range(meta.classes): if altNames is None: nameTag = meta.names[i] else: nameTag = altNames[i] res.append((nameTag, out[i])) res = sorted(res, key=lambda x: -x[1]) return res def detect(net, meta, image, thresh=.5, hier_thresh=.5, nms=.45, debug= False): """ Performs the meat of the detection """ #pylint: disable= C0321 im = load_image(image, 0, 0) if debug: print("Loaded image") ret = detect_image(net, meta, im, thresh, hier_thresh, nms, debug) free_image(im) if debug: print("freed image") return ret def detect_image(net, meta, im, thresh=.5, hier_thresh=.5, nms=.45, debug= False): #import cv2 #custom_image_bgr = cv2.imread(image) # use: detect(,,imagePath,) #custom_image = cv2.cvtColor(custom_image_bgr, cv2.COLOR_BGR2RGB) #custom_image = cv2.resize(custom_image,(lib.network_width(net), lib.network_height(net)), interpolation = cv2.INTER_LINEAR) #import scipy.misc #custom_image = scipy.misc.imread(image) #im, arr = array_to_image(custom_image) # you should comment line below: free_image(im) num = c_int(0) if debug: print("Assigned num") pnum = pointer(num) if debug: print("Assigned pnum") predict_image(net, im) letter_box = 0 #predict_image_letterbox(net, im) #letter_box = 1 if debug: print("did prediction") # dets = get_network_boxes(net, custom_image_bgr.shape[1], custom_image_bgr.shape[0], thresh, hier_thresh, None, 0, pnum, letter_box) # OpenCV dets = get_network_boxes(net, im.w, im.h, thresh, hier_thresh, None, 0, pnum, letter_box) if debug: print("Got dets") num = pnum[0] if debug: print("got zeroth index of pnum") if nms: do_nms_sort(dets, num, meta.classes, nms) if debug: print("did sort") res = [] if debug: print("about to range") for j in range(num): if debug: print("Ranging on "+str(j)+" of "+str(num)) if debug: print("Classes: "+str(meta), meta.classes, meta.names) for i in range(meta.classes): if debug: print("Class-ranging on "+str(i)+" of "+str(meta.classes)+"= "+str(dets[j].prob[i])) if dets[j].prob[i] > 0: b = dets[j].bbox if altNames is None: nameTag = meta.names[i] else: nameTag = altNames[i] if debug: print("Got bbox", b) print(nameTag) print(dets[j].prob[i]) print((b.x, b.y, b.w, b.h)) res.append((nameTag, dets[j].prob[i], (b.x, b.y, b.w, b.h))) if debug: print("did range") res = sorted(res, key=lambda x: -x[1]) if debug: print("did sort") free_detections(dets, num) if debug: print("freed detections") return res netMain = None metaMain = None altNames = None def performDetect(imagePath="data/dog.jpg", thresh= 0.25, configPath = "./cfg/yolov3.cfg", weightPath = "yolov3.weights", metaPath= "./cfg/coco.data", showImage= True, makeImageOnly = False, initOnly= False): """ Convenience function to handle the detection and returns of objects. Displaying bounding boxes requires libraries scikit-image and numpy Parameters ---------------- imagePath: str Path to the image to evaluate. Raises ValueError if not found thresh: float (default= 0.25) The detection threshold configPath: str Path to the configuration file. Raises ValueError if not found weightPath: str Path to the weights file. Raises ValueError if not found metaPath: str Path to the data file. Raises ValueError if not found showImage: bool (default= True) Compute (and show) bounding boxes. Changes return. makeImageOnly: bool (default= False) If showImage is True, this won't actually *show* the image, but will create the array and return it. initOnly: bool (default= False) Only initialize globals. Don't actually run a prediction. Returns ---------------------- When showImage is False, list of tuples like ('obj_label', confidence, (bounding_box_x_px, bounding_box_y_px, bounding_box_width_px, bounding_box_height_px)) The X and Y coordinates are from the center of the bounding box. Subtract half the width or height to get the lower corner. Otherwise, a dict with { "detections": as above "image": a numpy array representing an image, compatible with scikit-image "caption": an image caption } """ # Import the global variables. This lets us instance Darknet once, then just call performDetect() again without instancing again global metaMain, netMain, altNames #pylint: disable=W0603 assert 0 < thresh < 1, "Threshold should be a float between zero and one (non-inclusive)" if not os.path.exists(configPath): raise ValueError("Invalid config path `"+os.path.abspath(configPath)+"`") if not os.path.exists(weightPath): raise ValueError("Invalid weight path `"+os.path.abspath(weightPath)+"`") if not os.path.exists(metaPath): raise ValueError("Invalid data file path `"+os.path.abspath(metaPath)+"`") if netMain is None: netMain = load_net_custom(configPath.encode("ascii"), weightPath.encode("ascii"), 0, 1) # batch size = 1 if metaMain is None: metaMain = load_meta(metaPath.encode("ascii")) if altNames is None: # In Python 3, the metafile default access craps out on Windows (but not Linux) # Read the names file and create a list to feed to detect try: with open(metaPath) as metaFH: metaContents = metaFH.read() import re match = re.search("names *= *(.*)$", metaContents, re.IGNORECASE | re.MULTILINE) if match: result = match.group(1) else: result = None try: if os.path.exists(result): with open(result) as namesFH: namesList = namesFH.read().strip().split("\n") altNames = [x.strip() for x in namesList] except TypeError: pass except Exception: pass if initOnly: print("Initialized detector") return None if not os.path.exists(imagePath): raise ValueError("Invalid image path `"+os.path.abspath(imagePath)+"`") # Do the detection #detections = detect(netMain, metaMain, imagePath, thresh) # if is used cv2.imread(image) detections = detect(netMain, metaMain, imagePath.encode("ascii"), thresh) if showImage: try: from skimage import io, draw import numpy as np image = io.imread(imagePath) print("*** "+str(len(detections))+" Results, color coded by confidence ***") imcaption = [] for detection in detections: label = detection[0] confidence = detection[1] pstring = label+": "+str(np.rint(100 * confidence))+"%" imcaption.append(pstring) print(pstring) bounds = detection[2] shape = image.shape # x = shape[1] # xExtent = int(x * bounds[2] / 100) # y = shape[0] # yExtent = int(y * bounds[3] / 100) yExtent = int(bounds[3]) xEntent = int(bounds[2]) # Coordinates are around the center xCoord = int(bounds[0] - bounds[2]/2) yCoord = int(bounds[1] - bounds[3]/2) boundingBox = [ [xCoord, yCoord], [xCoord, yCoord + yExtent], [xCoord + xEntent, yCoord + yExtent], [xCoord + xEntent, yCoord] ] # Wiggle it around to make a 3px border rr, cc = draw.polygon_perimeter([x[1] for x in boundingBox], [x[0] for x in boundingBox], shape= shape) rr2, cc2 = draw.polygon_perimeter([x[1] + 1 for x in boundingBox], [x[0] for x in boundingBox], shape= shape) rr3, cc3 = draw.polygon_perimeter([x[1] - 1 for x in boundingBox], [x[0] for x in boundingBox], shape= shape) rr4, cc4 = draw.polygon_perimeter([x[1] for x in boundingBox], [x[0] + 1 for x in boundingBox], shape= shape) rr5, cc5 = draw.polygon_perimeter([x[1] for x in boundingBox], [x[0] - 1 for x in boundingBox], shape= shape) boxColor = (int(255 * (1 - (confidence ** 2))), int(255 * (confidence ** 2)), 0) draw.set_color(image, (rr, cc), boxColor, alpha= 0.8) draw.set_color(image, (rr2, cc2), boxColor, alpha= 0.8) draw.set_color(image, (rr3, cc3), boxColor, alpha= 0.8) draw.set_color(image, (rr4, cc4), boxColor, alpha= 0.8) draw.set_color(image, (rr5, cc5), boxColor, alpha= 0.8) if not makeImageOnly: io.imshow(image) io.show() detections = { "detections": detections, "image": image, "caption": "\n<br/>".join(imcaption) } except Exception as e: print("Unable to show image: "+str(e)) return detections if __name__ == "__main__": print(performDetect()) ```

程序无法启动。。。系统找不到指定文件

#include"stdafx.h" #include<afx.h> #include <opencv2/opencv.hpp> #include <iostream> using namespace cv; using namespace std; int main(){ CString abPath = "C:\\Profram Files\\feiq\\Recv Files\\ACSImage\\cache\\v3.2\\代表图"; getFile(abPath); } void changeSize(CString cs_abPath,string abSavePath,CString fileName){ Mat img = imread(cs_abPath.GetBuffer); Mat dst; string savePath = abSavePath +"\\" +fileName.GetBuffer+".jpg"; double scale; int img_height = img.rows; scale = 400.0/ img_height; resize(img, dst, Size(0, 0), scale, scale); imwrite(savePath,dst); } void getFile(CString pathStr){ CString myDataPath, fdPath; myDataPath =pathStr+"\\*.*"; CFileFind finder; boolean buffer = finder.FindFile(myDataPath); string abSavePath = "C:\\Profram Files\\feiq\\Recv Files\\ACSImage\\cache\\v3.2\\代表图小图"; while (buffer) { buffer = finder.FindNextFileW(); if (!finder.IsDots){ /*fdPath是当前的路径, 判断: 如果当前这个路径下是文件夹 递归(fdPath) 如果当前这个路径下是文件 则调changeSize() 多个文件的可以吗?? 保存文件的路径怎么办?? 逻辑上还是有问题 */ fdPath = finder.GetFilePath; if (finder.IsDirectory) { getFile(fdPath); } else { changeSize(fdPath, abSavePath, finder.GetFileName()); } } } finder.Close(); } 代码如上 win32AP 我想不用MFC然后调用MFC里的一些类, 出现题目所示问题. 1>------ Build started: Project: opencvTestBYljk, Configuration: Debug Win32 ------ 1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V120\Microsoft.CppBuild.targets(364,5): warning MSB8004: Output Directory does not end with a trailing slash. This build instance will add the slash as it is required to allow proper evaluation of the Output Directory. 1> opencvTestBYljk.cpp 1>d:\lx\home\proj\cuda\opencvtestbyljk\opencvtestbyljk\opencvtestbyljk.cpp(10): error C3861: 'getFile': identifier not found 1>d:\lx\home\proj\cuda\opencvtestbyljk\opencvtestbyljk\opencvtestbyljk.cpp(13): error C3867: 'ATL::CSimpleStringT<wchar_t,true>::GetBuffer': function call missing argument list; use '&ATL::CSimpleStringT<wchar_t,true>::GetBuffer' to create a pointer to member 1>d:\lx\home\proj\cuda\opencvtestbyljk\opencvtestbyljk\opencvtestbyljk.cpp(15): error C2678: binary '+' : no operator found which takes a left-hand operand of type 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>' (or there is no acceptable conversion) 1> d:\opencv249\opencv\build\include\opencv2\core\mat.hpp(2001): could be 'cv::MatConstIterator cv::operator +(ptrdiff_t,const cv::MatConstIterator &)' 1> d:\opencv249\opencv\build\include\opencv2\core\mat.hpp(1998): or 'cv::MatConstIterator cv::operator +(const cv::MatConstIterator &,ptrdiff_t)' 1> d:\opencv249\opencv\build\include\opencv2\core\mat.hpp(1268): or 'cv::MatExpr cv::operator +(const cv::MatExpr &,const cv::MatExpr &)' 1> d:\opencv249\opencv\build\include\opencv2\core\mat.hpp(1267): or 'cv::MatExpr cv::operator +(const cv::Scalar &,const cv::MatExpr &)' 1> d:\opencv249\opencv\build\include\opencv2\core\mat.hpp(1266): or 'cv::MatExpr cv::operator +(const cv::MatExpr &,const cv::Scalar &)' 1> d:\opencv249\opencv\build\include\opencv2\core\mat.hpp(1265): or 'cv::MatExpr cv::operator +(const cv::Mat &,const cv::MatExpr &)' 1> d:\opencv249\opencv\build\include\opencv2\core\mat.hpp(1264): or 'cv::MatExpr cv::operator +(const cv::MatExpr &,const cv::Mat &)' 1> d:\opencv249\opencv\build\include\opencv2\core\mat.hpp(1263): or 'cv::MatExpr cv::operator +(const cv::Scalar &,const cv::Mat &)' 1> d:\opencv249\opencv\build\include\opencv2\core\mat.hpp(1262): or 'cv::MatExpr cv::operator +(const cv::Mat &,const cv::Scalar &)' 1> d:\opencv249\opencv\build\include\opencv2\core\mat.hpp(1261): or 'cv::MatExpr cv::operator +(const cv::Mat &,const cv::Mat &)' 1> d:\opencv249\opencv\build\include\opencv2\core\operations.hpp(2248): or 'cv::Range cv::operator +(int,const cv::Range &)' 1> d:\opencv249\opencv\build\include\opencv2\core\operations.hpp(2243): or 'cv::Range cv::operator +(const cv::Range &,int)' 1> while trying to match the argument list '(std::basic_string<char,std::char_traits<char>,std::allocator<char>>, overloaded-function)' 1>d:\lx\home\proj\cuda\opencvtestbyljk\opencvtestbyljk\opencvtestbyljk.cpp(31): error C2276: '!' : illegal operation on bound member function expression 1>d:\lx\home\proj\cuda\opencvtestbyljk\opencvtestbyljk\opencvtestbyljk.cpp(40): error C3867: 'CFileFind::GetFilePath': function call missing argument list; use '&CFileFind::GetFilePath' to create a pointer to member 1>d:\lx\home\proj\cuda\opencvtestbyljk\opencvtestbyljk\opencvtestbyljk.cpp(40): error C2679: binary '=' : no operator found which takes a right-hand operand of type 'overloaded-function' (or there is no acceptable conversion) 1> d:\program files (x86)\microsoft visual studio 12.0\vc\atlmfc\include\cstringt.h(1322): could be 'ATL::CStringT<wchar_t,StrTraitMFC_DLL<wchar_t,ATL::ChTraitsCRT<wchar_t>>> &ATL::CStringT<wchar_t,StrTraitMFC_DLL<wchar_t,ATL::ChTraitsCRT<wchar_t>>>::operator =(const VARIANT &)' 1> d:\program files (x86)\microsoft visual studio 12.0\vc\atlmfc\include\cstringt.h(1314): or 'ATL::CStringT<wchar_t,StrTraitMFC_DLL<wchar_t,ATL::ChTraitsCRT<wchar_t>>> &ATL::CStringT<wchar_t,StrTraitMFC_DLL<wchar_t,ATL::ChTraitsCRT<wchar_t>>>::operator =(char)' 1> d:\program files (x86)\microsoft visual studio 12.0\vc\atlmfc\include\cstringt.h(1305): or 'ATL::CStringT<wchar_t,StrTraitMFC_DLL<wchar_t,ATL::ChTraitsCRT<wchar_t>>> &ATL::CStringT<wchar_t,StrTraitMFC_DLL<wchar_t,ATL::ChTraitsCRT<wchar_t>>>::operator =(wchar_t)' 1> d:\program files (x86)\microsoft visual studio 12.0\vc\atlmfc\include\cstringt.h(1299): or 'ATL::CStringT<wchar_t,StrTraitMFC_DLL<wchar_t,ATL::ChTraitsCRT<wchar_t>>> &ATL::CStringT<wchar_t,StrTraitMFC_DLL<wchar_t,ATL::ChTraitsCRT<wchar_t>>>::operator =(const unsigned char *)' 1> d:\program files (x86)\microsoft visual studio 12.0\vc\atlmfc\include\cstringt.h(1281): or 'ATL::CStringT<wchar_t,StrTraitMFC_DLL<wchar_t,ATL::ChTraitsCRT<wchar_t>>> &ATL::CStringT<wchar_t,StrTraitMFC_DLL<wchar_t,ATL::ChTraitsCRT<wchar_t>>>::operator =(const char *)' 1> d:\program files (x86)\microsoft visual studio 12.0\vc\atlmfc\include\cstringt.h(1273): or 'ATL::CStringT<wchar_t,StrTraitMFC_DLL<wchar_t,ATL::ChTraitsCRT<wchar_t>>> &ATL::CStringT<wchar_t,StrTraitMFC_DLL<wchar_t,ATL::ChTraitsCRT<wchar_t>>>::operator =(const wchar_t *)' 1> d:\program files (x86)\microsoft visual studio 12.0\vc\atlmfc\include\cstringt.h(1258): or 'ATL::CStringT<wchar_t,StrTraitMFC_DLL<wchar_t,ATL::ChTraitsCRT<wchar_t>>> &ATL::CStringT<wchar_t,StrTraitMFC_DLL<wchar_t,ATL::ChTraitsCRT<wchar_t>>>::operator =(const ATL::CStringT<wchar_t,StrTraitMFC_DLL<wchar_t,ATL::ChTraitsCRT<wchar_t>>> &)' 1> while trying to match the argument list '(CString, overloaded-function)' 1>d:\lx\home\proj\cuda\opencvtestbyljk\opencvtestbyljk\opencvtestbyljk.cpp(41): error C3867: 'CFileFind::IsDirectory': function call missing argument list; use '&CFileFind::IsDirectory' to create a pointer to member

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

程序员请照顾好自己,周末病魔差点一套带走我。

程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

搜狗输入法也在挑战国人的智商!

故事总是一个接着一个到来...上周写完《鲁大师已经彻底沦为一款垃圾流氓软件!》这篇文章之后,鲁大师的市场工作人员就找到了我,希望把这篇文章删除掉。经过一番沟通我先把这篇文章从公号中删除了...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

2020阿里全球数学大赛:3万名高手、4道题、2天2夜未交卷

阿里巴巴全球数学竞赛( Alibaba Global Mathematics Competition)由马云发起,由中国科学技术协会、阿里巴巴基金会、阿里巴巴达摩院共同举办。大赛不设报名门槛,全世界爱好数学的人都可参与,不论是否出身数学专业、是否投身数学研究。 2020年阿里巴巴达摩院邀请北京大学、剑桥大学、浙江大学等高校的顶尖数学教师组建了出题组。中科院院士、美国艺术与科学院院士、北京国际数学...

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

程序员为什么千万不要瞎努力?

本文作者用对比非常鲜明的两个开发团队的故事,讲解了敏捷开发之道 —— 如果你的团队缺乏统一标准的环境,那么即使勤劳努力,不仅会极其耗时而且成果甚微,使用...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发(16k)

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

《Oracle Java SE编程自学与面试指南》最佳学习路线图2020年最新版(进大厂必备)

正确选择比瞎努力更重要!

《Oracle Java SE编程自学与面试指南》最佳学习路线图(2020最新版)

正确选择比瞎努力更重要!

都前后端分离了,咱就别做页面跳转了!统统 JSON 交互

文章目录1. 无状态登录1.1 什么是有状态1.2 什么是无状态1.3 如何实现无状态1.4 各自优缺点2. 登录交互2.1 前后端分离的数据交互2.2 登录成功2.3 登录失败3. 未认证处理方案4. 注销登录 这是本系列的第四篇,有小伙伴找不到之前文章,松哥给大家列一个索引出来: 挖一个大坑,Spring Security 开搞! 松哥手把手带你入门 Spring Security,别再问密...

字节跳动面试官竟然问了我JDBC?

轻松等回家通知

面试官:你连SSO都不懂,就别来面试了

大厂竟然要考我SSO,卧槽。

阿里面试官让我用Zk(Zookeeper)实现分布式锁

他可能没想到,我当场手写出来了

终于,月薪过5万了!

来看几个问题想不想月薪超过5万?想不想进入公司架构组?想不想成为项目组的负责人?想不想成为spring的高手,超越99%的对手?那么本文内容是你必须要掌握的。本文主要详解bean的生命...

自从喜欢上了B站这12个UP主,我越来越觉得自己是个废柴了!

不怕告诉你,我自从喜欢上了这12个UP主,哔哩哔哩成为了我手机上最耗电的软件,几乎每天都会看,可是吧,看的越多,我就越觉得自己是个废柴,唉,老天不公啊,不信你看看…… 间接性踌躇满志,持续性混吃等死,都是因为你们……但是,自己的学习力在慢慢变强,这是不容忽视的,推荐给你们! 都说B站是个宝,可是有人不会挖啊,没事,今天咱挖好的送你一箩筐,首先啊,我在B站上最喜欢看这个家伙的视频了,为啥 ,咱撇...

代码注释如此沙雕,会玩还是你们程序员!

某站后端代码被“开源”,同时刷遍全网的,还有代码里的那些神注释。 我们这才知道,原来程序员个个都是段子手;这么多年来,我们也走过了他们的无数套路… 首先,产品经理,是永远永远吐槽不完的!网友的评论也非常扎心,说看这些代码就像在阅读程序员的日记,每一页都写满了对产品经理的恨。 然后,也要发出直击灵魂的质问:你是尊贵的付费大会员吗? 这不禁让人想起之前某音乐app的穷逼Vip,果然,穷逼在哪里都是...

立即提问
相关内容推荐