import cv2 import numpy as np def main(): # 1.导入图片 img_src = cv2.imread("cc.jpg") # 2.灰度化,二值化 img_gray = cv2.cvtColor(img_src, cv2.COLOR_BGR2GRAY) ret, img_bin = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY) # 3.连通域分析 img_bin, contours, hierarchy = cv2.findContours(img_bin, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) # 4.获取最小外接矩形并打印 min_rect = cv2.minAreaRect(contours[0]) print("返回值min_rect:\n", min_rect) rect_points = cv2.boxPoints(min_rect) print("返回值rect_points:\n", rect_points) rect_points = np.int0(rect_points) # 5.绘制最小外接矩形 img_result = img_src.copy() cv2.drawContours(img_result, [rect_points], 0, (255, 255, 255), 2) # 6.显示结果图片 cv2.imshow("img_src", img_src) cv2.imshow("img_result", img_result) cv2.waitKey() cv2.destroyAllWindows() if __name__ == '__main__': main()怎么把图像摆正
时间: 2024-03-11 09:50:29 浏览: 166
要将图像摆正,您可以使用cv2.warpAffine()函数。该函数使用变换矩阵将图像旋转、平移、缩放等转换。以下是一个示例,可以将最小外接矩形旋转到水平方向:
```python
# 计算旋转角度
angle = min_rect[2]
if angle < -45:
angle += 90
# 计算旋转中心
center = tuple(np.array(img_src.shape[1::-1]) / 2)
# 生成变换矩阵
M = cv2.getRotationMatrix2D(center, angle, 1)
# 应用变换矩阵
img_result_rotated = cv2.warpAffine(img_result, M, img_src.shape[1::-1], flags=cv2.INTER_CUBIC)
```
这将生成一个旋转后的图像img_result_rotated。您可以将其保存为图像文件并使用cv2.imshow()函数显示。
相关问题
import cv2 import numpy as np def cv_show(name,img): cv2.imshow(name,img) cv2.waitKey() cv2.destroyAllWindows() def get_img(path1,path2): img1 = cv2.imread(path1) img2 = cv2.imread(path2) img1 = cv2.resize(img1, (300, 400)) img2 = cv2.resize(img2, (300, 400)) #原图像变换为灰度图 img1_gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) img2_gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY) return img1,img2,img1_gray,img2_gray def get_info(img1_gray,img2_gray): # 尺度不变特征变换 sift = cv2.SIFT_create() # 关键点以及特征向量计算 kp1, des1 = sift.detectAndCompute(img1_gray, None) kp2, des2 = sift.detectAndCompute(img2_gray, None) kp1 = np.float32([kp.pt for kp in kp1]) kp2 = np.float32([kp.pt for kp in kp2]) return kp1,des1,kp2,des2 def get_match(kp1,kp2,des1,des2): # 特征点交叉检验 bf = cv2.BFMatcher() matches = bf.knnMatch(des1, des2,k=2) idx_pair=[] for m,n in matches: if m.distance<n.distance*0.75: idx_pair.append((m.queryIdx,m.trainIdx)) if len(idx_pair)>4: pt_list1 = np.float32([kp1[i] for (i, _) in idx_pair]) pt_list2 = np.float32([kp1[i] for (_, i) in idx_pair]) H,_ = cv2.findHomography(pt_list2,pt_list1,cv.RANSAC,4) result = cv2.warpPerspective(img2, H, (img1.shape[1] + img2.shape[1], img1.shape[0])) result[0:img1.shape[0], 0:img1.shape[1]] = img1 return result #main函数 path1='img1.jpg' path2='img2.jpg' img1,img2,img1_gray,img2_gray=get_img(path1,path2) kp1,des1,kp2,des2=get_info(img1_gray,img2_gray) result=get_match(kp1,des1,kp2,des2) cv_show('result',result)对以上代码debug
这段代码的功能是将两张图片进行拼接,其中使用了SIFT算法进行特征点提取和匹配,以及RANSAC算法计算单应性矩阵。对于代码本身,我看到以下几个问题:
1.第一行的import语句应该写在不同的行中,而不是在同一行中。
2.在函数get_match()中,第12行的cv.RANSAC应该改为cv2.RANSAC。
3.在函数get_match()中,第20行的kp1应该改为kp2。
4.在函数get_match()中,第22行的img2应该改为img1。
5.在主函数中,img1和img2的大小应该保持一致,否则无法进行拼接。
6.在主函数中,应该调用cv_show()函数来显示img1和img2,以便查看它们的内容。
7.在主函数中,应该将result保存为文件,而不是直接展示在屏幕上。
希望我的解答能够帮助到你!
import cv2 import numpy as np import PIL.ImageDraw SCALE = 0.65156853729882650681169151675877 # m/px def add_chinese_text(img, text, position, textColor, textSize): img = PIL.Image.fromarray(img) draw = PIL.ImageDraw.Draw(img) fontStyle = PIL.ImageFont.truetype('simsun.ttc', textSize, encoding='utf-8') draw.text(position, text, textColor, font=fontStyle, stroke_width=1) return np.asarray(img) def main(): # 读取verts with open('verts.txt', 'r', encoding='utf8') as f: verts = f.readlines() verts = list(map(lambda x: x.split(), verts)) verts = list(map(lambda x: [x[0], int(x[1]), int(x[2])], verts)) print(f'{verts=}') # 读取edges with open('edges.txt', 'r', encoding='utf8') as f: edges = f.readlines() edges = list(map(lambda x: x.split(), edges)) edges = list(map(lambda x: [int(x[0]), int(x[1])], edges)) print(f'{edges=}') # 显示地图 im = cv2.imread('map.png') for edge in edges: v1 = verts[edge[0]] # 边关联的点1 v2 = verts[edge[1]] # 边关联的点2 weight = int((((v1[1] - v2[1]) ** 2 + (v1[2] - v2[2]) ** 2) ** 0.5) * SCALE) # 权重为两点欧氏距离 cv2.line(im, (v1[1], v1[2]), (v2[1], v2[2]), (255, 0, 0), 5) # 绘制边的直线 im = add_chinese_text(im, str(weight), ((v1[1] + v2[1]) // 2, (v1[2] + v2[2]) // 2), (255, 0, 255), 30) # 绘制边的权重 for i, vert in enumerate(verts): cv2.circle(im, (vert[1], vert[2]), 20, (255, 0, 0), 2) # 绘制顶点圆圈 im = add_chinese_text(im, str(i), (vert[1] - 15, vert[2] - 15), (255, 0, 255), 30) # 绘制顶点圈中序号数字 im = add_chinese_text(im, vert[0], (vert[1] - 40, vert[2] + 25), (255, 0, 255), 30) # 绘制顶点下方文字 cv2.namedWindow('map', cv2.WINDOW_KEEPRATIO) cv2.imshow('map', im) cv2.waitKey() if __name__ == '__main__': main()
这段代码导入了三个模块:
1. cv2:这是一个用于计算机视觉的库,可以用来处理图像和视频数据。
2. numpy:这是一个用于科学计算的库,主要用于处理数组和矩阵的运算。
3. PIL.ImageDraw:这是 Python Imaging Library (PIL) 中的一个模块,用于在图像上绘图。
SCALE 这个常量的值是一个浮点数,代表一个缩放比例。
阅读全文