农作物不使用opencv为此图像起作用
我需要通过使用OpenCV检测图像的坐标来裁剪以下图像。 我尝试了以下代码,但它无法正常工作。
import cv2
#reading image
image = cv2.imread("input.PNG")
#converting to gray scale
gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
#applying canny edge detection
edged = cv2.Canny(image, 10, 250)
#finding contours
(_, cnts, _) = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
idx = 0
for c in cnts:
x,y,w,h = cv2.boundingRect(c)
if w>50 and h>50:
idx+=1
new_img=image[y:y+h,x:x+w]
#cropping images
cv2.imwrite("cropped/"+str(idx) + '.png', new_img)
#cv2.imshow("Original Image",image)
#cv2.imshow("Canny Edge",edged)
#cv2.waitKey(0)
输入图像:
输出映像:
i need to crop the below image by detecting co-ordinates of the image using opencv.
i tried below code but it's not working as expected.
import cv2
#reading image
image = cv2.imread("input.PNG")
#converting to gray scale
gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
#applying canny edge detection
edged = cv2.Canny(image, 10, 250)
#finding contours
(_, cnts, _) = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
idx = 0
for c in cnts:
x,y,w,h = cv2.boundingRect(c)
if w>50 and h>50:
idx+=1
new_img=image[y:y+h,x:x+w]
#cropping images
cv2.imwrite("cropped/"+str(idx) + '.png', new_img)
#cv2.imshow("Original Image",image)
#cv2.imshow("Canny Edge",edged)
#cv2.waitKey(0)
Input Image:
Output image:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
基于从
cv2.boundingRect()
返回的坐标裁剪图像不会给您带来所需的结果。您需要获取图像的4个角并相应地将其定向。这也可以使用透视转换矩阵完成,检测边缘,后来找到轮廓不是正确的方法。您需要找到足够大的轮廓以封闭整个页面。为此,对图像进行二进制并找到最大的外部轮廓。
代码:
结果:
Cropping the image based on coordinates returned from
cv2.boundingRect()
will not give you the desired result. You need to obtain the 4 corners of the image and orient it accordingly. This can be done using the perspective transformation matrixAlso, detecting edges and later finding contours is not the right way to go. You need to find a contour large enough to enclose the entire page. To do so, binarize the image and find the largest external contour.
Code:
Result: