我有一张图像,稍后我必须以特定格式读取图像,我必须找到轮廓并将所有轮廓图像写入指定的输出文件夹。然后,我必须在文件名下创建子文件夹,并将分段的图像写入相关文件夹。到现在为止,我能够以指定的格式读取图像,而能够找到轮廓,但无法将所有轮廓图像写入特定的文件夹中。
import cv2
import os, os.path
print (cv2.__version__)
imageDir = "C:/Users/animesh.singh/Downloads/Assignment/" #specify your path here
image_path_list = []
valid_image_extensions = [".jpg", ".jpeg", ".png", ".tif", ".tiff"]
#specify your valid extensions here
valid_image_extensions = [item.lower() for item in valid_image_extensions]
for file in os.listdir(imageDir):
extension = os.path.splitext(file)[1]
if extension.lower() not in valid_image_extensions:
continue
image_path_list.append(os.path.join(imageDir, file))
for imagePath in image_path_list:
img = cv2.imread(imagePath)
if img is None:
continue
cv2.imshow(imagePath, img)
key = cv2.waitKey(0)
if key == 27: # escape
break
cv2.destroyAllWindows()
for imagePath in image_path_list:
ret, thresh = cv2.threshold(img,0,255,cv2.THRESH_BINARY_INV)
edges = cv2.Canny(img, 100, 200)
cv2.imshow(imagePath,thresh)
cv2.imshow(imagePath,edges)
key = cv2.waitKey(0)
cv2.destroyAllWindows()
contours, hierarchy = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
cv2.drawContours(img, [contour], 0, (0, 0, 255), 3)
cv2.imwrite('C:/Users/animesh.singh/Downloads/Assignment/contour_images/1 (103)_N_0_0_CARD_Contour_Output.jpg', img)
我想要:
•从文件夹中读取所有图像,该图像接受PDF以外的所有图像格式。
•查找轮廓并将所有轮廓图像写入到指定的输出文件夹中。
•在文件名下创建子文件夹,并将分段的图像写入相关文件夹。
输入图像:
1:
2:
3:
答案 0 :(得分:0)
您的代码当前正在执行的操作是在图像上绘制轮廓线,然后将其保存。它仅对image_path_list
中的最后一张图片执行此操作,并且由于imwrite
是硬编码的,因此将始终仅生成1张图片。
这是每个图像应遵循的过程: - 新建一个文件夹 -在图像中找到轮廓 -对于每个轮廓,请使用boundingRect,即包含轮廓的框 -使用boundingrect的尺寸来创建子图像 -使用变量名称保存子图像。
下面的代码显示了1张图片的处理过程,您可以在for imagePath in image_path_list:
代码:
import cv2
import numpy as np
import os
from os import listdir
# get the filenames in directory
basepath = "C:/Users/Desktop/Images/"
files = listdir(basepath)
# declare valid filtypes
valid_image_extensions = [".jpg", ".jpeg", ".png", ".tif", ".tiff"]
for name in files:
# check if it is a valid filetype
filename, file_extension = os.path.splitext(name)
if file_extension in valid_image_extensions:
# create a folder for this image
path = basepath+filename
if not os.path.exists(path):
os.makedirs(path)
# load image in grayscale
img = cv2.imread(basepath+name,0)
# threshold image
ret,mask = cv2.threshold(img,240,255,cv2.THRESH_BINARY_INV)
# find contours
ret, contours, hier = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for i in range(len(contours)):
# get contour
cnt = contours[i]
# get the dimensions of the boundingRect
x,y,w,h = cv2.boundingRect(cnt)
# create a subimage based on boundingRect
sub_img = img[y:y+h,x:x+w]
# save image of contour with indexed name
cv2.imwrite(path+"\contour_"+str(i)+".jpg", sub_img)