编辑:我通过向图像添加2位帧,然后使用我的代码,最后裁剪图像以删除额外的帧来绕过问题.这是一个丑陋的解决方案,但它的工作原理!
我遇到了一个问题,我不确定这是一个错误还是我缺乏经验.我会尽可能清楚地总结一下:
我得到一个二进制图像,其中包含我想要分析的彩色图像的轮廓(白色像素是我的算法检测到的轮廓的周长,其余为黑色).图像非常复杂,因为我想要检测的对象完全填充图像(没有"背景").
我对该图像使用findcontours:
contours, hierarchy = cv2.findContours(image,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_NONE)
Run Code Online (Sandbox Code Playgroud)然后"for"循环检测面积小于"X"像素的轮廓和hierarchy[0][x][3] >= 0(让我们调用新数组"contours_2")
我在新图像中绘制"contours_2":
cv2.drawContours(image=image2, contours=contours_2, contourIdx=-1, color=(255,255,255), thickness=-1)
Run Code Online (Sandbox Code Playgroud)问题是drawcontours绘制所有轮廓都很好,但它不会"填充"图像边界中的轮廓(也就是说,图像边缘有一个边界的轮廓).我尝试将图像的边框像素(如框架)设置为True,但它不起作用,因为findcontours会自动将这些像素设置为零(在函数说明中).
使用cv2.contourArea在前面的回路检测的轮廓以及返回正常值,所以没有办法知道当一个轮廓将drawcontours被忽略,什么时候会填写正确.cv2.isContourConvex根本不起作用,因为每个轮廓返回为假.
我可以在绘制它们之前使用cv2.convexHull绘制那些"边缘"轮廓,但我只需要在边缘上使用它(因为它会使轮廓变形并且我想尽可能地避免这种情况).问题是......我无法检测哪些轮廓位于图像的边缘,哪些轮廓不是,并且使用drawcontours可以正常工作.
所以我想问为什么drawContour表现得那样,如果有一些方法可以让它填充边缘的轮廓.或者,另一种解决方案是找到如何检测图像边界中的轮廓(因此我可以在需要时应用凸包).
2017年的新标准增加了std::filesystem.使用它,我如何计算目录中的文件(包括子目录)的数量?
我知道我们可以这样做:
std::size_t number_of_files_in_directory(std::filesystem::path path)
{
std::size_t number_of_files = 0u;
for (auto const & file : std::filesystem::directory_iterator(path))
{
++number_of_files;
}
return number_of_files;
}
Run Code Online (Sandbox Code Playgroud)
但这似乎有点矫枉过正.是否存在更简单,更快捷的方法?
我有两个列表list1和list2数字,我想用相同的指令迭代它们.像这样:
for item in list1:
print(item.amount)
print(item.total_amount)
for item in list2:
print(item.amount)
print(item.total_amount)
Run Code Online (Sandbox Code Playgroud)
但这感觉多余.我知道我可以写for item in list1 + list2:,但它有运行时间的代价.
没有宽松的时间,有没有办法做到这一点?
我有一些在Python中编写的代码,其输出是一个numpy数组,现在我想将该输出发送到C++代码,其中将执行大量的计算.
我尝试过使用cython public cdef,但我正在运行一些问题.非常感谢你的帮助!这是我的代码:
pymodule.pyx:
from pythonmodule import result # result is my numpy array
import numpy as np
cimport numpy as np
cimport cython
@cython.boundscheck(False)
@cython.wraparound(False)
cdef public void cfunc():
print 'I am in here!!!'
cdef np.ndarray[np.float64_t, ndim=2, mode='c'] res = result
print res
Run Code Online (Sandbox Code Playgroud)
一旦进行了cython化,我打电话给:
pymain.c:
#include <Python.h>
#include <numpy/arrayobject.h>
#include "pymodule.h"
int main() {
Py_Initialize();
initpymodule();
test(2);
Py_Finalize();
}
int test(int a)
{
Py_Initialize();
initpymodule();
cfunc();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我得到一个NameError为result …
从迭代中删除项目通常会导致RuntimeError: dictionary changed size during iteration异常:
d = {1: 2}
# exception raised
for k in d:
del d[k]
Run Code Online (Sandbox Code Playgroud)
更确切地说,删除本身将成功.但是,要进入下一轮迭代,解释器必须调用next(it),it通过之前获得的字典,迭代器在哪里.此时,next()会注意到字典大小发生了变化,并抱怨.
到现在为止还挺好.但是如果我们都删除并添加项目到字典呢?
d = {1: 1}
# no exception raised
for k in d:
# order of next two lines doesn't matter
d[k*10] = k*10
del d[k]
Run Code Online (Sandbox Code Playgroud)
我几乎可以肯定这不安全(文档暗示在迭代期间不允许插入或删除).为什么解释器允许此代码无错运行?
我唯一的猜测是,每当调用insert或delete方法时,检查哪些迭代器无效是太昂贵了.所以dict不要尝试完善提出这个例外.相反,它只是跟踪每个迭代器内部字典的大小,并在实际要求迭代器移动到下一个项目时检查它是否未更改.有没有办法能够以低成本实现全面验证?
我使用的是aiohttp和sqlalchemy,和我创建了一个单身,帮助我,当我需要的SQLAlchemy(代码如下)的实例连接.不幸的是,每隔一段时间我就会收到以下错误(我通过重启服务器"解决"):
12月11日09:35:29 ip-xxx-xxx-xxx-xxx gunicorn [16513]:sqlalchemy.exc.StatementError:(sqlalchemy.exc.InvalidRequestError)在无效事务回滚之前无法重新连接[SQL:'.. .\nFROM ... \nWHERE ... =%(username_1)s \n LIMIT%(param_1)s'] [参数:[{}]]```
有没有办法修复当前的代码?谢谢 :)
CONNECTION_DETAILS = {
'driver': 'pymysql',
'dialect': 'mysql',
'host': os.environ.get('HOST'),
'port': 3306,
'user': 'master',
'password': os.environ.get('PASSWORD'),
'database': 'ourdb',
'charset': 'utf8'
}
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
con_str = '{dialect}+{driver}://{user}:{password}@' \
'{host}:{port}/{database}?charset={charset}'\
.format(**cls.CONNECTION_DETAILS)
try:
engine = sqlalchemy.create_engine(con_str)
Session = scoped_session(sessionmaker(bind=engine))
session = Session() # Create the ORM handle
except sqlalchemy.exc.OperationalError:
logger.exception('Establishing database connection error.')
cls._instance = super().__new__(cls)
logger.debug("Returning …Run Code Online (Sandbox Code Playgroud) 什么是正确的类型提示x = []?
我的 PyCharm 编辑器中的类型检查器将此标记为错误:
labelframes: List[ttk.LabelFrame] = []
Run Code Online (Sandbox Code Playgroud)
'Optional' 不是一个选项,如:
labelframes: List[Optional[ttk.LabelFrame]] = []
Run Code Online (Sandbox Code Playgroud)
因为文档typing.Optional说明这相当于:
labelframes: List[Union[ttk.LabelFrame, None]] = []
Run Code Online (Sandbox Code Playgroud)
并且[None]不是[]。
我应该提到 PyCharm 也不喜欢这样:
labelframes: List[Union[ttk.LabelFrame, None]] = [None]
Run Code Online (Sandbox Code Playgroud)
无论我尝试什么类型的提示。PyCharm 将其标记为错误,“预期在此处返回我的类型提示,但没有返回”,因此我尝试了:
labelframes: Optional[List[ttk.LabelFrame, None]] = []
Run Code Online (Sandbox Code Playgroud)
那没有用。
我知道 PEP 526 有许多遵循以下模式的示例:
x: List[str] = []
Run Code Online (Sandbox Code Playgroud) 在Python 3.6中,您可以使用以下f字符串:
>>> date = datetime.date(1991, 10, 12)
>>> f'{date} was on a {date:%A}'
'1991-10-12 was on a Saturday'
Run Code Online (Sandbox Code Playgroud)
我想重载接收'%A'上述方法的方法.可以吗?
例如,如果我想写一个愚蠢的包装器datetime,我可能期望这个重载看起来像:
class MyDatetime:
def __init__(self, my_datetime, some_other_value):
self.dt = my_datetime
self.some_other_value = some_other_value
def __fstr__(self, format_str):
return (
self.dt.strftime(format_str) +
'some other string' +
str(self.some_other_value
)
Run Code Online (Sandbox Code Playgroud) 我需要创建一个包含某些运行结果的箱形图 - 对于每个运行,我都有最小输出,最大输出,平均输出和标准偏差.这意味着我将需要16个带有标签的箱形图.
到目前为止我遇到的例子描绘了一个数字分布,但在我的情况下,这是不可行的.
在Python(Matplotlib)/ R中有没有办法做到这一点?
'Hello ' + 1 在Python 3.5和3.6上没有返回相同的错误消息:
TypeError: Can't convert 'int' object to str implicitlyTypeError: must be str, not int这是一个简单的措辞改变还是有更微妙的背后?
python ×9
python-3.x ×5
c++ ×2
python-3.6 ×2
aiohttp ×1
arrays ×1
c++17 ×1
cython ×1
dictionary ×1
f-string ×1
iteration ×1
list ×1
loops ×1
matplotlib ×1
numpy ×1
opencv ×1
pymysql ×1
python-3.5 ×1
r ×1
sqlalchemy ×1
string ×1
type-hinting ×1
typeerror ×1
typing ×1